Skip to content

Instantly share code, notes, and snippets.

@jbochi
Created March 16, 2014 17:35
Show Gist options
  • Save jbochi/9586916 to your computer and use it in GitHub Desktop.
Save jbochi/9586916 to your computer and use it in GitHub Desktop.
Como "pausar/suspender" execução código C com corotina Lua
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
double arg;
static int l_csleep_cont (lua_State *L) {
printf("continuando!\n");
lua_pushnumber(L, arg);
return 1;
}
static int l_csleep (lua_State *L) {
arg = luaL_checknumber(L, 1);
return lua_yieldk(L, 0, 0, l_csleep_cont);
}
int main (void) {
char *buff = "return csleep(10)";
int status;
lua_State *L = luaL_newstate();
lua_State *thread;
luaL_openlibs(L);
lua_pushcfunction(L, l_csleep);
lua_setglobal(L, "csleep");
thread = lua_newthread(L);
status = luaL_loadbuffer(thread, buff, strlen(buff), "line") ||
lua_resume(thread, NULL, 0);
while (status == LUA_YIELD) {
printf("cedeu a vez: ");
printf("%s\n", lua_tostring(thread, -1));
status = lua_resume(thread, thread, 0);
}
if (status == LUA_ERRRUN) {
fprintf(stderr, "ERRO: %s\n", lua_tostring(thread, -1));
lua_pop(L, 1); /* pop error message from the stack */
return 1;
} else {
const char *retval = lua_tostring(thread, -1);
printf("Retorno: %s\n", retval);
}
lua_close(L);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment