2
** $Id: lcorolib.c,v 1.5.1.1 2013/04/12 18:48:47 roberto Exp $
4
** See Copyright Notice in lua.h
20
static int auxresume (lua_State *L, lua_State *co, int narg) {
22
if (!lua_checkstack(co, narg)) {
23
lua_pushliteral(L, "too many arguments to resume");
24
return -1; /* error flag */
26
if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {
27
lua_pushliteral(L, "cannot resume dead coroutine");
28
return -1; /* error flag */
30
lua_xmove(L, co, narg);
31
status = lua_resume(co, L, narg);
32
if (status == LUA_OK || status == LUA_YIELD) {
33
int nres = lua_gettop(co);
34
if (!lua_checkstack(L, nres + 1)) {
35
lua_pop(co, nres); /* remove results anyway */
36
lua_pushliteral(L, "too many results to resume");
37
return -1; /* error flag */
39
lua_xmove(co, L, nres); /* move yielded values */
43
lua_xmove(co, L, 1); /* move error message */
44
return -1; /* error flag */
49
static int luaB_coresume (lua_State *L) {
50
lua_State *co = lua_tothread(L, 1);
52
luaL_argcheck(L, co, 1, "coroutine expected");
53
r = auxresume(L, co, lua_gettop(L) - 1);
55
lua_pushboolean(L, 0);
57
return 2; /* return false + error message */
60
lua_pushboolean(L, 1);
61
lua_insert(L, -(r + 1));
62
return r + 1; /* return true + `resume' returns */
67
static int luaB_auxwrap (lua_State *L) {
68
lua_State *co = lua_tothread(L, lua_upvalueindex(1));
69
int r = auxresume(L, co, lua_gettop(L));
71
if (lua_isstring(L, -1)) { /* error object is a string? */
72
luaL_where(L, 1); /* add extra info */
76
return lua_error(L); /* propagate error */
82
static int luaB_cocreate (lua_State *L) {
84
luaL_checktype(L, 1, LUA_TFUNCTION);
85
NL = lua_newthread(L);
86
lua_pushvalue(L, 1); /* move function to top */
87
lua_xmove(L, NL, 1); /* move function from L to NL */
92
static int luaB_cowrap (lua_State *L) {
94
lua_pushcclosure(L, luaB_auxwrap, 1);
99
static int luaB_yield (lua_State *L) {
100
return lua_yield(L, lua_gettop(L));
104
static int luaB_costatus (lua_State *L) {
105
lua_State *co = lua_tothread(L, 1);
106
luaL_argcheck(L, co, 1, "coroutine expected");
107
if (L == co) lua_pushliteral(L, "running");
109
switch (lua_status(co)) {
111
lua_pushliteral(L, "suspended");
115
if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
116
lua_pushliteral(L, "normal"); /* it is running */
117
else if (lua_gettop(co) == 0)
118
lua_pushliteral(L, "dead");
120
lua_pushliteral(L, "suspended"); /* initial state */
123
default: /* some error occurred */
124
lua_pushliteral(L, "dead");
132
static int luaB_corunning (lua_State *L) {
133
int ismain = lua_pushthread(L);
134
lua_pushboolean(L, ismain);
139
static const luaL_Reg co_funcs[] = {
140
{"create", luaB_cocreate},
141
{"resume", luaB_coresume},
142
{"running", luaB_corunning},
143
{"status", luaB_costatus},
144
{"wrap", luaB_cowrap},
145
{"yield", luaB_yield},
151
LUAMOD_API int luaopen_coroutine (lua_State *L) {
152
luaL_newlib(L, co_funcs);