lua-users home
lua-l archive

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

Coincidently, I just finally got *my* garbage collection working.  A few months back, I wrote the list because I had implemented garbage collection, but none of the gc functions were being called.  Here's some helpful information:
- when the "gc" tag method is called, on the top of the stack is the userdata object.  This object normally points to the memory location you want to free.  You can get this object using the void *lua_touserdata(lua_State *L, 1)  ("1" because the userdata object is at the top of the stack).  Cast the void* pointer to the proper type, then delete the variable (or free() the memory, if you're using c).
- the "gc" tag method can only be set for userdata.  The reason my garbage collection didn't work all this time was because I had set the "gc" tag method for a *table* tag.  If you do this, there will be no warning, but no "gc" tag method will be called.
also, here's some other helpful troubleshooting information Edgar Toernig and Roberto sent me when I had my problems:
Some things you should check: First, are you using the correct tag in all
places? Does the userdata get the right one? Is the gc-method set for
the same? Then, are you sure you do not create additional references to
your selection userdata? Example:
    function foo()
        local x = make_selection(...) -- returns the userdata
        y = x
Here after executing foo you still have a reference to your selection
in the global y. And as long as this reference exists your gc-method
will not be called! An y=nil/0/""/... is required to remove this ref-
erence. It's not like in some languages that the destruction of x calls
the destructor (the gc-method). Destroying the last reference to an
object calls it. And last, did you create references within the C
program via lua_ref(L, 1)? Make sure that _each_ lua_ref call has the
appropriate lua_unref (and this can't be in the gc-method!).
Hope all this helps,
-----Original Message-----
From: Jens Wessling []
Sent: Tuesday, July 24, 2001 8:12 AM
To: Multiple recipients of list
Subject: "gc" tag method.

Hello all,
I am trying to tie in to the garbage collection system.  My (current) question is this: when my "gc" function is called, how do I know what memory is being freed?  I would like to tie in so that I can delete the memory on my side that Lua is not using any more, but I don't know what that memory is?  How do I, with only the lua_State pointer, find out what memory is being collected?
Jens Wessling