Hi,
Thanks for your reply. My intention is to create 2 totally independent lua scripts running in parallel. So I run them in completely separate Lua States since I don't want their global space to overlap.
I figured out that I was never yielding from the coroutine so I fixed my code like this which is working good. So now I want to write a module in C which when called from Lua would allow the lua program to run multiple lua scripts simultaneously without needing any support from the OS.
My program now is:
#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 = "for i = 1,5 do print('x'..tostring(i)) end";
char* prog2 = "for i = 1,10 do print('y'..tostring(i)) 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,4);
lua_sethook(thread2,(lua_Hook) hookFunc,LUA_MASKCOUNT,4);
lua_resume(thread1,0);
flag=1;
lua_resume(thread2,0);
while(lua_status(thread1) || lua_status(thread2))
{
if (flag==0)
{
flag = 1;
if (lua_status(thread2))
lua_resume(thread2,0);
}
else
{
flag = 0;
if (lua_status(thread1))
lua_resume(thread1,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;
}