lua-users home
lua-l archive

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


2011/1/7 Roberto Ierusalimschy <roberto@inf.puc-rio.br>:
>> I would be happy to see refs go away because they seem like a sharp,
>> tempting feature that actually doesn't add value.
>>
>> If your userdata object needs to reference other Lua data, you
>> really, really, really want to use the environment mechanism because
>> this works with the GC whereas refs are very prone to creating
>> uncollectable cycles.
>>
>> If your C code needs to reference a Lua value, I tend to recommend
>> using light userdata keys in the registry bearing in mind that this
>> creates anchors for the GC.
>
> Exactly. The archetypal use of references were a full userdata keeping
> references to other Lua values by keeping in its C structure the
> integers returned by luaL_ref. The finalizer for this userdata should be
> responsible to release its references when the userdata was collected.
> This kind of use became obsolete with environments.
>
> Does anyone still use references in real applications? For what?

I use it when I need to pass a callback to a C library, that could be
triggered in a subsequent lib call (ie. I can't just let a value on
the stack). I allocate a small struct { lua_State* L; int ref },
create a ref to the callback (a Lua "function" passed by the binding
user) and pass its address as the callback void*.

Of course luaL_ref is easy to implement, and since it's seldom used it
could go away. On the other hand a good (IMHO) reason to keep it in
the official API is that it somehow declares the array part of the
registry as the right place to store such references, and it tells
anyone that want to store stuff in that part of the registry to play
nice with "reference keepers".