lua-users home
lua-l archive

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

On 8/22/05, Rici Lake <> wrote:

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.

Actually i'm using tolua and the __gc metametod should delete the object, by calling delete.
Besides that, these objects may also be created inside lua scripts, and in this case i'd like that lua takes care of their disposal. 

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?

This can't happen, i set up every reference every time i call the function, and the functions which use "external" references aren't callable by other lua functions.

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).

I'm non sure I understand this. It happens quite often to have more than one reference to the same object; I don't see where is the problem in creating a new pointer each time.

--A Arri