lua-users home
lua-l archive

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

Dear Lua list,

I'm trying to provide a "wait" function for the scripts that I call from C++ code, so that we can write e.g. wait(5) and the script waits for 5 seconds, while the rest of the program continues to run. That is, my situation is very similar to John Haggertys description at <>, just my question is a bit different:

Whenever I use lua_newthread() to start a new coroutine, according to the PiL2 I have to anchor the new thread value somewhere in the Lua state, so that it is not garbage collected ahead of time.

Thus, my first attempt was to make a new table in the registry, and the put the thread as a key(!) into that table. As the value for that key I would use the number of seconds remaining to wait.
That is, using the C API, I do the equivalent of

This is nice and simple, e.g. I can easily iterate over the TableInRegistry key/value pairs and check for and update the WaitTimeLeft and resume the thread when it dropped to zero.

The problem is, once a thread returned normally (body function completed without yield()), I'd do
*but* setting nil here still won't ever garbage collect the thread, does it?

Well... I was wondering how to best solve the problem. (And if my assumption above that the thread is never collected is right?)

One solution is of course to index the TableInRegistry with something other than the threads, e.g. a unique thread-ID number maintained by the C++ code. The values of that table would then be the threads, or small sub-tables each containing a thread and the related WaitTimeLeft.

Anyways, I was wondering if there is anything better than that, or if I'm overlooking something obvious.

Many thanks in advance, and best regards,

Ca3D - Engine
Carsten Fuchs