lua-users home
lua-l archive

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


* David Ludwig:

> The memory of a coroutine's lua_State can get garbage collected and
> freed automatically, whereas the top-level state's memory will not get
> freed unless specifically asked.  This can be a problem if a
> coroutine's code calls a C function, which then records the pointer of
> the passed-in lua_State.  If the coroutine ends and its state gets
> freed, the C-side code may end up crashing if it tries to use that
> lua_State.  One fix to this is to use the top-level state.

It's usually recommended to update the stored Lua state pointer with
the current call's state prior to calling back into Lua.

I struggled with this problem, too, and it's shared by other language
interfaces (notably JNI).  You can store the current Lua state in a
thread-local variable if you want to accept this operating system
dependency.

> One portable way to deal with this is to store a pointer to the
> top-level state as a userdata in the global environment.  It's not the
> fastest solution, however it may be fast enough depending on what
> you're writing.

Would it also be possible to allocate a dedicated Lua thread for this
purpose?