# How to keep track of threads in LUA?

This topic is 3413 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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_THREADS		5

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 libs
lua_State *Lua = lua_open();
luaL_openlibs(Lua);

lua_register(Lua, "Wait", luaWait);

// call Main function from script

getchar();

getchar();

}


And test.lua looks like this...
function Main()
print("In Main function")
Wait()
print("Leaving Main function")
end


And the output is as follows... In LUA Main function Thread is paused.. (then after I press return) Leaving Main function So 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. )

##### Share on other sites
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

##### Share on other sites
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).

1. 1
2. 2
3. 3
Rutin
18
4. 4
5. 5
JoeJ
13

• 14
• 10
• 24
• 9
• 57
• ### Forum Statistics

• Total Topics
632639
• Total Posts
3007613
• ### Who's Online (See full list)

There are no registered users currently online

×