lua-users home
lua-l archive

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


FWIW, here is an implementation of what Roberto just described:

https://github.com/brimworks/lua-ev/blob/master/obj_lua_ev.c

Specifically, create_obj_registry() creates the weak table
register_obj() is used to add a reference to this "object registry",
and push_objs() is used to map the pointers back into their lua
counter-parts.

The watcher_cb() function uses the push_objs() function:

https://github.com/brimworks/lua-ev/blob/master/watcher_lua_ev.c#L132

As a side-note, you need to be sure to keep references to your lua
userdata callbacks to prevent them from getting GC'ed (of course).
However, you don't want to keep those references in the lua registry
otherwise you will have memory leaks when two callbacks reference each
other (via their callback closures).  The only way I found around this
problem was to keep references in the fenv() of the userdata.

Here is an example: test_is_pending()

https://github.com/brimworks/lua-ev/blob/master/test/test_ev_timer.lua#L132

My original design had a memory leak after running that test.

Cheers,
-Brian

On Thu, Mar 24, 2011 at 9:52 AM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>> Is there a better way? In other words, can I push the userdata on
>> the stack given only the pointer to that userdata? That would be
>> nnnnnice.
>
> There is a simpler solution, but not that simpler. You can keep a
> map from light userdata (the pointer to the userdata) to the
> userdata themselves.
>
> Nevertheless, this map still must be kept in a weak table if you want
> Lua to colect the userdata. (But that seems dangerous if other parts of
> your code keep a pointer to it.)
>
> -- Roberto
>
>
>



-- 
Brian Maher >> Glory to God <<