lua-users home
lua-l archive

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


On Mon, Jan 2, 2012 at 11:50 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2012/1/3 Patrick Rapin <toupie300@gmail.com>:
>
>> You can take the address of the full userdata block, push the address
>> on the stack as a light userdata, and use that light userdata as a key
>> to store the full one into the registry (or any other table).
>
> That will solve the problem underlying my post.  My userdata structure
> contains pointers to other userdata, and I need functions returning
> those to Lua as full userdata.

Whats the lifetime relationship between the parent userdata and its
children/components?

If the parent has to exist as long as any children are being
referenced, you can create
full userdata for the children that is only big enough to hold the
pointer, create an environment table for the children, and put the
parent userdata into the children's environment.

If you want to avoid creating multiple child userdata for the same
child pointer, then putting it in a weak valued table that maps
lightuserdata of the pointer to the full userdata is useful. Then when
a child is being returned you can check to see if a child userdata
already exists, and return it if it does, otherwise creating a new one
and storing it by pointer. This shouldn't cause memory leaks, the
child userdatas will get GCed when they are no longer being referenced
by lua code.

A possible problem with storing userdata in global/singleton tables
that aren't weak (like the registry) is that they will stay there
forever if not removed... I tend to do that when C code needs to find
userdata, and only has

Cheers,
Sam