lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


After reading the "lua_State and garbage collection" thread in http://mirrors.dotsrc.org/lua/lua-l-recent.gz I decided to look into luaL_ref. So I googled for "luaL_ref lua_newthread" and found this gem: http://sourceforge.net/mailarchive/forum.php?thread_id=5756641&forum_id=32657

The key part of it is saving a reference to the thread:

thread_reference = luaL_ref(L,LUA_REGISTRYINDEX);

and then you can release it with:

luaL_unref (L,LUA_REGISTRYINDEX,thread_reference);

It seems to have cured a null reference exception I was getting in C# due to the (apparently) thread being garbage collected.

Is this the right way?


David Morris-Oliveros wrote:
The way that I'm terminating the thread is by preempting them out, and then removing the reference to them from the global lua table.

I am in charge of multitasking all my coroutines, and i have a class that encapsulates the coroutine, so i keep a variable with the "state" of the thread at any given time, NOT_LOADED, STARTING, RUNNING, SLEEPING, DEAD, KILLED.

So if it's DEAD (because it's finished running), i just clean it up. But I can force the clean up by setting it to KILLED, then removing the references to it from the main globals.

Hope this helps, and hope that I'm not doing anything stupid.

David Andersen wrote:

I was reading through the mailing list and I saw that you can forcibly stop a thread by removing all trace of it from the stack. I'm pretty new to lua, so I'm wondering if anyone can point me in the right direction. I am looking for the correct C API commands to use to pop from the stack. I'm afraid of introducing a memory leak.

Maybe its really easy and I just need to call :

threadState = lua_newthread(L);
<do stuff>
lua_pop(threadState, lua_gettop(threadState));

I am using the technique found in this posting to run AI scripts for a game, so I have lots of threads, and they need to be terminated immediately when the object they are attached to dies.

http://www.icynorth.com/forums/viewtopic.php?p=228&sid=4b08243f0dd2ebe6b8b416fe0bc4eeb4#228