lua-users home
lua-l archive

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

I am trying to use the coroutine functionality in Lua 5.0w0 to break
a script to the surrounding C code so that the C code in turn can
break out and allow stuff to happen and cooperative task switching
to take place in a surrounding non-C context in which the calling C
code is embedded.

After some experimentation, I found that something like the following
seems to mostly work:

  lua_State *L = lua_open();
  lua_register(L, "breakout", breakout);
  lua_dobuffer(L, script, length, NULL);
  lua_getglobal(L, "main");
  lua_cobegin(L, 0);
  while (0 == lua_resume(L, L)) {
    /* Do something or other */

int breakout(lua_State *L) {
 return lua_yield(L, 0);

Still, questions remain:
- Where is documentation of the coroutine C API?
- Is the above legal usage? In particular, is it allowable to pass the
same lua state into both parameters of lua_resume?
- Is it possible to achieve the same without a special function in
the lua script (main() in the above example), that is, break out and
resume the top level script instead of some function embedded in it?
- Is it possible to yield on a regular basis, e.g. every few opcodes,
without having to pepper the script with yields?