lua-users home
lua-l archive

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





On 7 January 2011 15:36, Mark Hamburg <mark@grubmah.com> wrote:
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.

Mark

But if you have the data to create a light userdata then you already have an id which is a pointer.
 

On 7 January 2011 16:07, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> > That is a good question. Since userdata got "environments" in 5.1
> > (called uservalues, in 5.2), the need for luaL_ref diminished a lot.
> >
> > -- Roberto
> >
> Not so much that it is going to be removed I hope, how else would C code
> keep a reference to Lua data without generating its own id mechanism?

For a fixed number of references there are several ways (e.g., unique
strings or addresses of C static variables). For dynamic creation of new
references there are several ways, too. One is to use a lightuserdata
as a key, as Mark suggested. (If the refered object is a userdata, its
address is a perfect key.) Another is to use your own table inside
the registry to keep only your references. (This table may be weak,
solving the GC problem.)

-- Roberto

"If the refered object is a userdata"
What if it is not, would the following still be valid?
If a Lua function returns a Lua function which you want to store in C/C++ thus enabling calls to it at a later date. Would it be valid to cast the function on the stack to a userdata (void*) and push this as the key, storing the void* in C?

As for a GC problem some people using [C++] (inserted other languages here) and refs create a scoped wrapper which unregisters a valid reference when it goes out of scope. It is also nice that the references are ints allowing raw gets.


Liam