lua-users home
lua-l archive

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

Hello Again,

This is a matter of how you want to manage your code.
For the g_SpriteVector, I would have this as a global held in C++, that menas there is no mem-managing to do.
For the object held in the vector, thats a little harder.
I am assuming that you are holding fairly plain C/C++ code in the vector (as per you previous mail). And when Lua requests it you wrapper it and pass it back to Lua.
In this case, the C++ should be managing the code. And its C++'s job to delete the objects when required.
The issue is that if someone within Lua requests a sprite, and then C++ deletes it, the lua object is still valid, but it points to dead memory (core dump anyone?).
So I suggest that you document this behaviour and tell people not to keep references to a sprite within lua, but get them as they need it.

As an alternative (there are always so many ways to solve the problem), you could let Lua manage the data, this menas you will need a __gc method in your metatable to delete the C++ object & probably tell the vector to remove it as well.

If you asked for an opinion, I would use the former, rather than the latter.


> Thanks! The fact is, I've never worked with Lua metatables before. I'm glad
> it
> turned out to be as simple as it is.
> I am currently storing pointers to Lua userdata in g_SpriteVector. Do I have
> to
> watch out for the Lua garbage collector? Could it free the memory of a
> sprite
> structure while I still have a pointer to it?