#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int flag = 0;
lua_State *luaVM1, *luaVM2, *thread1, *thread2;
int hookFunc(lua_State *L, lua_Debug *dbg);
int main(int argc, char* argv[ ])
{
luaVM1 = luaL_newstate();
luaVM2 = luaL_newstate();
luaL_openlibs(luaVM1);
luaL_openlibs(luaVM2);
thread1 = lua_newthread(luaVM1);
thread2 = lua_newthread(luaVM2);
if (NULL == luaVM1 || NULL == luaVM2)
{
printf("Error Initializing lua\n");
return -1;
}
char* prog1 = "function co() while true do for i=1,100 do"
" print('B') end coroutine.yield() end end"
" c = coroutine.create(co) coroutine.resume(c)"
" while true do for i=1,70 do print('A') end"
" coroutine.resume(c) end";
char* prog2 = "while true do print('C') end";
// Create threads in each lua state
// Now push the function into the stack of each thread
luaL_loadstring(thread1,prog1);
luaL_loadstring(thread2,prog2);
lua_sethook(thread1,(lua_Hook) hookFunc,LUA_MASKCOUNT,500);
lua_sethook(thread2,(lua_Hook) hookFunc,LUA_MASKCOUNT,500);
lua_resume(thread1,0,0);
flag=1;
lua_resume(thread2,0,0);
while(lua_status(thread1) || lua_status(thread2))
{
if (flag==0)
{
flag = 1;
if (lua_status(thread2))
lua_resume(thread2,0,0);
}
else
{
flag = 0;
if (lua_status(thread1))
lua_resume(thread1,0,0);
}
}
lua_close( luaVM1 );
lua_close( luaVM2 );
return 0;
}
int hookFunc(lua_State *L, lua_Debug *dbg)
{
//printf("Hook Called\n");
if(flag==0)
{
//printf("Flag0\n");
return lua_yield(thread1,0);
}
else
{
//printf("flag1\n");
return lua_yield(thread2,0);
}
return 0;
}
/*
./a.out | uniq -c | head
100 B
70 A
21 B
125 C
48 A
125 C
120 A
125 C
120 A
125 C
*/