lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


here is an example:

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

static int report (lua_State *L, int status) {
 const char *msg;
 if (status) {
   msg = lua_tostring(L, -1);
   if (msg == NULL) msg = "(error with no message)";
   fprintf(stderr, "%s\n", msg);
   lua_pop(L, 1);
 }
 return status;
}

int main(int argc, char *argv[])
{
 lua_State *L = lua_open();

 luaopen_base(L);
 luaopen_table(L);
 luaopen_io(L);
 luaopen_string(L);
 luaopen_math(L);
 luaopen_debug(L);

 if(argc>1) {
   int status, i;
   lua_State *C = lua_newthread(L);
   printf("loading %s\n", argv[1]);
   if (report(C, luaL_loadfile(C, argv[1]) )) exit(1);

   printf("starting\n");
   for (i=0; i<10; i++) {
     if (report(C, lua_resume(C, 0) )) exit(2);
     printf("i = %d\n", i);
   }
 }

 lua_setgcthreshold(L, 0);  // collected garbage
 lua_close(L);
 return 0;
}


$ cat app.lua

not_dead_yet = true

while not_dead_yet do
 print'one'
 coroutine.yield(1)

 print'two'
 coroutine.yield(2)

 print'three'
 coroutine.yield(3)
end

$ ./a app.lua
loading app.lua
starting
one
i = 0
two
i = 1
three
i = 2
one
i = 3
two
i = 4
three
i = 5
one
i = 6
two
i = 7
three
i = 8
one
i = 9

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus