lua-users home
lua-l archive

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


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.

-- 
Javier

Attachment: signature.asc
Description: This is a digitally signed message part.