[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: garbage collector question
- From: Rici Lake <lua@...>
- Date: Mon, 22 Aug 2005 11:48:19 -0500
On 22-Aug-05, at 10:58 AM, Alberto Arri wrote:
I'm developing a C++ program which uses lua as scripting language. I
need lua to interact with C++ classes, so i'm using full user data of
the size of a pointer to store the address of the object. Now
sometimes i have to pass objects created in my c code to lua
functions; as far as i have understood, the gc will from this moment
keep track of these objects and try to free them when they aren't in
use anymore by lua. But they are still in use by my program, which
will free them on his own when it's the time.
Keeping a Lua userdata containing a pointer to an object is different
from allocating the object directly in a Lua userdata. Lua will
automatically free the storage it allocates; in the former case, that
means it will free the pointer; in the latter case, it means it will
free the object.
Before doing that, Lua will also run the __gc metamethod, if it finds
one in the userdata's metatable. Unless you've set up a __gc metamethod
which calls free() on the pointer in the userdata, the original object
pointed to will be untouched. That's probably what you wanted.
However, there are a couple of things to think about:
1) What happens if you delete an object which the Lua script still has
a reference to?
2) Do you want to cache userdata for object pointers, or are you happy
with creating a new one each time? (You may need to cache if object
identity is important, or if you're likely to create a lot of
references to the same C++ object).