lua-users home
lua-l archive

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

Peter Loveday wrote:

I do something identical to this in a project; the userdata pointer in Lua
is exactly the same as any C++ reference to the object in the way it is
reference counted.  As you say, the gc just decrements the count.  This
also works well with multiple Lua references to the same object via
different userdata objects (in 4.1), as each different one just holds a
ref on the object.

How do you pass your userdata object into Lua calls? That is, say I have C++ code that wants to call a function like:

int doSomething(MyObject* obj);

...where obj exists in both C++ and Lua. If doSomething were a wrapper to a Lua function, you would have to push the name of the function, and then the argument. If you can't keep a weak reference to the userdata object in Lua, how would you push obj onto the Lua stack?

Hmm, now that I think about it...I guess I could just call newuserdatabox(), as there's no reason why I need to use the exact same Lua object for the call. Then I can increment my refcount, and GC will be called once for every Lua instance of the userdata. That *could* create a whole mess of duplicate userdata's that need collecting but it would work. I'll have to get a rough estimate of how many extra objects I'd be creating with this approach.

Thanks for the insight, much appreciated.


I don't have the requirement of C++ having a Lua table, as in this example,
but I can't see why that wouldn't work more or less the same way; Lua maintains
the refcount, C++ can effectively hold a ref as long as it likes, and release
it when it wants.

Love, Light and Peace,
- Peter Loveday
eyeon Software