   How to keep track of threads in LUA?
  Hi guys,I've started using LUA very recently, and I'm looking for a technique how to keep track of threads. I'm sure the solution is a simple one, here's a code example...#define MAX_THREADS5lua_State *Thread[MAX_THREADS];int luaWait(lua_State *L){int val = 0;//How can I tell that I'm in Thread[3] here?val = lua_yield(L, 0);return val;}void main(){// open lua and std libslua_State *Lua = lua_open();luaL_openlibs(Lua);lua_register(Lua, "Wait", luaWait);// create a threadThread[3] = lua_newthread(Lua);luaL_dofile(Thread[3], "waittest.lua");// call Main function from scriptlua_getglobal(Thread[3], "Main");lua_resume(Thread[3], 0);printf( "Thread is paused.." );getchar();//resume yielded threadlua_resume(Thread[3], 0);getchar();}And test.lua looks like this...function Main()print("In Main function")Wait()print("Leaving Main function")endAnd the output is as follows...In LUA Main functionThread is paused..(then after I press return)Leaving Main functionSo it's all working as expected. My question is this... how can I tell what thread called the luaWait function from inside that function? (the intention is to have multiple threads running at once, hence the array. I've just fired off number [3] as an example. )   
  If your not going to do true threading ( ie run each state in a true OS thread ), you can just push a global to indicate what is the current active Lua state at anyone time. If you intend to do run each Lua state in a OS thread, you can store the Lua thread ID inside the Lua state itself and fetch it when u need it (store it as a global Lua variable called _Thread_ID or something ). Also since you have access to the Lua state like so :int luaWait(lua_State *L)you can compare it against the array (lua_State *Thread[MAX_THREADS]) to find the match. This should also work. Be aware if you actually want to run multiple scripts in a unique OS thread, that your C API is also thread safe.Good Luck!-ddn   ;  Thanks for the reply. The simplest method is always the easiest one eh! I actually found an alternative solution. For the benefit of others with the same problem, I actually ended up doing this...lua_pushlightuserdata(Thread[3], Thread[3]);lua_pushinteger(Thread[3],3);lua_settable(Thread[3],LUA_GLOBALSINDEX);during initilization of the threads, then inside the luaWait function...lua_pushlightuserdata(L, L);lua_gettable(L,LUA_GLOBALSINDEX);int ThreadNumber = lua_tointeger(L,-1); //Got the thread number... which I believe is using the address of the thread as a key in a table (which will be unique to the thread, and which I'll have inside the luaWait function).   