lua-users home
lua-l archive

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



On 21-Feb-07, at 12:02 PM, Wesley Smith wrote:

Hi everyone,
I have a C library I've wrapped that requires generating alot of
userdata variables.  Alot of times though, the userdata variables are
equivalent one one's that already exist.  As an example, I'll generate
a variable called a dBody and another one called a dGeom which I then
link together.  Later on, I can ask the dGeom for it's attached body
and I will get a pointer to a dBody that already exists.

Currently, I'm doing instance counting and call lua_newuserdata()
whenever I want to push copies of a userdata into Lua.  When __gc is
called, I check how many instances of it exist and free it only when
the one being deleted will result in a count of 0.

To break the problem down a bit more, if I copy userdata from the Lua
side, Lua takes care of instance counting, but in my case, I'm copying
userdata from the C side and I am doing the instance counting.  My
userdata is boxed pointers and I'm wondering if there's anything to be
gained from keeping track of the handle to my userdata the Lua uses
and the pointer to the data that the C library functions actually use
such that when I get the data pointer, I can look up its Lua handle in
a table and push that instead of calling lua_newuserdata()?  Is there
a way I can give lua a userdata pointer and somehow get the variable
to the top of the stack so that I can return it from a C function,
effectively doing the copy in Lua, causing Lua to do instance counting
for me?

The simplest way is to keep a weak-valued table whose keys are lightuserdata (the pointer to the c structure) and whose values are the equivalent userdata object (containing the boxed pointer).