From 96e15b8501e5d8fc40c475cbac573f910ab5853b Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Fri, 25 Oct 2002 17:05:28 -0300 Subject: threads now are real Lua objects, subject to garbage collection --- lbaselib.c | 76 ++++++++++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 34 deletions(-) (limited to 'lbaselib.c') diff --git a/lbaselib.c b/lbaselib.c index 4ef2cb3e..1d8f8abf 100644 --- a/lbaselib.c +++ b/lbaselib.c @@ -1,5 +1,5 @@ /* -** $Id: lbaselib.c,v 1.99 2002/09/16 19:49:45 roberto Exp roberto $ +** $Id: lbaselib.c,v 1.100 2002/10/22 19:41:08 roberto Exp roberto $ ** Basic library ** See Copyright Notice in lua.h */ @@ -362,6 +362,9 @@ static int luaB_tostring (lua_State *L) { case LUA_TLIGHTUSERDATA: sprintf(buff, "userdata: %p", lua_touserdata(L, 1)); break; + case LUA_TTHREAD: + sprintf(buff, "thread: %p", (void *)lua_tothread(L, 1)); + break; case LUA_TNIL: lua_pushliteral(L, "nil"); return 1; @@ -535,26 +538,40 @@ static const luaL_reg base_funcs[] = { */ -static int luaB_resume (lua_State *L) { - lua_State *co = (lua_State *)lua_unboxpointer(L, lua_upvalueindex(1)); +static int luaB_auxresume (lua_State *L, lua_State *co) { int status; - lua_settop(L, 0); + int oldtop = lua_gettop(L); status = lua_resume(L, co); - if (status != 0) - return lua_error(L); - return lua_gettop(L); + return (status != 0) ? -1 : lua_gettop(L) - oldtop; } +static int luaB_coresume (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + int r; + luaL_arg_check(L, co, 1, "coroutine/thread expected"); + r = luaB_auxresume(L, co); + if (r < 0) { + lua_pushboolean(L, 0); + lua_insert(L, -2); + return 2; /* return false + error message */ + } + else { + lua_pushboolean(L, 1); + lua_insert(L, -(r + 1)); + return r + 1; /* return true + `resume' returns */ + } +} + -static int gc_coroutine (lua_State *L) { - lua_State *co = (lua_State *)lua_unboxpointer(L, 1); - lua_closethread(L, co); - return 0; +static int luaB_auxwrap (lua_State *L) { + int r = luaB_auxresume(L, lua_tothread(L, lua_upvalueindex(1))); + if (r < 0) lua_error(L); + return r; } -static int luaB_coroutine (lua_State *L) { +static int luaB_cocreate (lua_State *L) { lua_State *NL; int ref; int i; @@ -562,20 +579,21 @@ static int luaB_coroutine (lua_State *L) { luaL_arg_check(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, "Lua function expected"); NL = lua_newthread(L); - if (NL == NULL) return luaL_error(L, "unable to create new thread"); /* move function and arguments from L to NL */ - for (i=0; i