lua-users home
lua-l archive

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


On Sat, Jun 6, 2009 at 12:52 PM, Sam Roberts<vieuxtech@gmail.com> wrote:
> On Sat, Jun 6, 2009 at 6:27 AM, David Ludwig<dludwig@pobox.com> wrote:
>> 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.
>
> The C code shouldn't be storeing L this long, it should be using the L
> passed to it.
>
> Sam


Here's a simple example of why you would need this:

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.


wes