lua-users home
lua-l archive

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

Ok, in my mind there is a large difference between a "local" and a "value". A program can "create" a hundred local variables, and return them to C, and call other functions with them, without ever requiring the gc to free them. They just exist on the stack, and so get automatically "freed" when the stack shrinks or is reused.

Some "values" that you can store in a local variable require garbage collection though. From the moment you create them (tables userdata and closures) the garbage collector will attempt to find them, and if it can't it'll free them. It does this by inspecting locals, traversing tables, traversing function prototypes, etc.

So in answer to your question, the garbage collector "kicks in" from the moment the userdata is created. Some time after the last reference to the userdata is removed, it can be freed. This is why you need to keep strings and userdata on the stack until you're completely done working with them - so that lua doesn't free them. But you never know when this is going to occur. So if your userdata needs to release expensive resources you should do it manually when you are done using it, and only use the __gc method to catch cases like where an error thrown prevented you from doing it manually.

See and for more info.

- Alex

----- Original Message ----- From: liam mail If a Lua (5.1) function creates a local variable(actually it is a userdata and metatable with __gc method set ) and returns it to Cpp pushing it onto the stack, when does the garbage collector kick in for this variable.? Is it when the value is popped off the stack that the variable becomes "no longer active" or at a later time?