lua-users home
lua-l archive

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

I don't have the first problem. Actually our binding library was designed and implemented so that for each C++ object exported to lua, it has a corresponding lua table, which minimics an "object" in lua, which you can manuplate with and call class methods exported from c++. The lightuserdata was a entry on this table so that when calling the object methods or access the object attributes, our binding library can find the right C++ object to work with. Also the "__gc" method is bind to this table, so that whenever this table was abondoned, the table is reclaimed. When the __gc metamethod is called, the C++ object is also cleaned. Sorry for not explain it clearly in the first message.
Thanks all for your suggestions. It looks now the best solution is to use userdata to allocate memory for C++ objects. I'll go back look at our binding library source and see if there is any trouble doing so.


2008/11/14 Javier Guerra Giraldez <>
On Friday 14 November 2008, Cheng, Long wrote:
> lua VM does not think there are enough "wasted memory" to reclaim. I'm
> just wondering is there any way I can tell the GC algorithm how much
> "external" memory the lightuserdata is referencing? Or is there other
> "proper" ways to handle the objects life cycle? Thanks!

there are two related problems:

- as Matias has noted, lightuserdata doesn't have a __gc.  that is because,
being 'light', they're just values, as numbers, or booleans.  the 'reference'
part is done by your C(++) code, so it's not a Lua thing.

- even if you use 'full' userdatas with __gc, if all you store there is a
pointer to your (potentially heavy) C++ object, Lua's GC doesn't have a clue
that keeping this tiny 4-byte object around implies keeping a much bigger
object on the C side.

in general, when a not-so-heavy Lua object is backed by a more expensive
resource (might be a memory hog, or an open file, or a DB connection,
whatever), you need some way for your program to explicitly close the object.
Of course, the __gc of an 'open' object should properly close it too.

The Lua object might not be collected immediately; but the C++ side should be.
after that, any access to the Lua object should result in an error.

in short, just add a 'close' method to the Lua object, and call it as soon as
you don't need it.