lua-users home
lua-l archive

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



> I first create a global state using lua_open(). Subsequently, I create C++
> objects that have zero or more associated Lua scripts. For each script I
> create a thread under the global state using lua_newthread(), which loads
> and initializes the script using luaL_loadfile() and lua_pcall(). At this
> point, the script is blocked on a lua_yield() waiting for an event to occur.

> There are no hard references to the thread on the Lua side as far as I know.

> I was under the impression, perhaps falsely, that a thread will not be garbage
> collected if it's status is not dead (i.e. it's currently suspended and waiting
> to be resumed). In any case, the crash I'm experiencing occurs on the invocation
> of lua_pcall() after a script is loaded by a new thread. Here's a GDB backtrace...

If there is no reference to the thread in Lua, the thread may be garbage
collected at any moment (except when it is running). So you must keep a
reference to it.

You should probably use luaL_ref and keep the reference indexes in your
C++ objects.

When you call lua_newthread(L), the new thread object will be placed on L's
stack. If you don't pop it from that stack, then the thread is not garbage
collectable, assuming that L is not garbage collectable (i.e., L is the
main thread). Of course, it may not be a good idea to just let things
accumulate on the main stack.

A thread is garbage collectable precisely when no references to it remain
(in Lua), regardless of its "state". (Threads in Lua are not really threads
the way you might be thinking of them; they don't really "block". The best
way to think of them, imho, is as separate execution stacks.)

From the stack trace, it looks to me like the thread is running and is trying
to put something in a table, rather than crashing on the invocation of pcall.
It is hard to know what the problem is; it may or may not be related to
garbage collection.