Skip to content

Instantly share code, notes, and snippets.

@aniruddha-a
Created September 13, 2013 06:20
Show Gist options
  • Save aniruddha-a/6547238 to your computer and use it in GitHub Desktop.
Save aniruddha-a/6547238 to your computer and use it in GitHub Desktop.
Start a Lua coroutine from C (with a function that can yield) - Lua5.1
#include <stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
static int
doyield (lua_State *T)
{
return lua_yield (T, 0);
}
int main (int argc, char *argv[])
{
lua_State *L = luaL_newstate();
int ret;
char *file = "testcoro.lua";
luaL_openlibs(L);
/* Register a C function which does a yield*/
lua_register(L, "yieldme" , doyield);
/* Load the Lua chunk on the main state */
if (luaL_dofile(L, file) != 0) {
fprintf(stderr,"Failed to load file\n");
exit(1);
}
lua_State *l1 = lua_newthread(L);
lua_getglobal(l1, "corobegin"); // coro start func
// push args if any
do {
ret = lua_resume(l1, 0); // no args
if (pret == LUA_YIELD) {
// nothing much
} else if (pret == 0) {
// coro ended with no errors
} else {
fprintf(stderr, "\nFailed to resume: %s\n", lua_tostring(l1, -1));
}
} while (ret == LUA_YIELD);
return 0;
}
#if 0
testcoro.lua:
function corobegin
for i=1,5 do
yieldme()
end
end
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment