lua-users home
lua-l archive

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


Am 21.12.10 17:35, schrieb Henk Boom:
> On 21 December 2010 10:59, Marc Balmer <marc@msys.ch> wrote:
>> In Lua, I create a hierarchy of "objects" (Lua tables) that finally
>> represent a GUI widget hierarchy.
>>
>> Now I want to somehow store C data in these objects, or link them with
>> such information.
>>
>> E.g. I have to store the Widget pointer (a C lightuserdata value) for
>> each widget represented in the hierarchy.
>>
>> What is a good way to do this?  My adventourous approach at the moment
>> is to create an additional table when an object is created, store my
>> values in this additional table and add it as metatable to the created
>> object...
> 
> I'd start by saying that the easiest way is to simply store the values
> a a field on the table. Something hidden-looking (like ._c_data) might
> be good enough for your use.

That is what I am doing now.  It seems to work nicely, the widgets are
created, the callbacks work, everything is glued together.

It's fun to program X and Motif in Lua ;)

> 
> A more insulated way is to use a weak-keyed table, similar to what you
> were suggesting. Something like this:
> 
> local data_table = setmetatable({}, {__mode='k'})
> function attach_value(table, data)
>   data_table[table] = data
> end
> 
> function get_value(table)
>   return data_table[table]
> end
> 
> If the table is garbage collected, its entry is automatically  removed
> from the table. The downside to this approach is that if 'data' is an
> object which refers directly or indirectly to 'table', they will never
> be collected. If it's a lightuserdata though there shouldn't be a
> problem. In Lua 5.2 this issue is supposed to be completely resolved.
> 
>     henk
>