[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: retrieve top-level lua_State?
- From: Peter Cawley <lua@...>
- Date: Sat, 6 Jun 2009 20:28:04 +0100
On Sat, Jun 6, 2009 at 7:02 PM, Wesley Smith<firstname.lastname@example.org> wrote:
> Let's say you have a userdata that performs a callback into the
> lua_State based on events received C-side. To actually do the
> callback, you need a pointer to the lua_State that the userdata
> belongs, which must be stored in the userdata.
> It's not hard to see a situation where the userdata gets created in a
> coroutine but then is subsequently used outside of that coroutine such
> that when a callback is made, it uses the coroutine's lua_State which
> may have already been collected, causing a crash.
I think that a lua_getmainthread function would be a good addition to
the API, however this situation can be avoided.
First, C code can detect if it was called from the main thread
(lua_pushthread(L) will return 1). It could enforce a policy of being
only called from the main thread, throwing an error if it wasn't.
Alternatively, when creating userdata with callbacks, if it's not
called from the main thread, then it should keep a reference to the
thread which created the userdata in the userdata environment table,
thus ensuring that the thread will not be collected before the
userdata. If I setup a callback from a thread, then I would expect
callbacks to be made to that thread rather than the main thread, even
though that prevents the thread from being collected.