Lua Garbage collector - the __gc metamethod


Example

5.2

Objects in lua are garbage collected. Sometimes, you need to free some resource, want to print a message or do something else when an object is destroyed (collected). For this, you can use the __gc metamethod, which gets called with the object as argument when the object is destroyed. You could see this metamethod as a sort of destructor.

This example shows the __gc metamethod in action. When the inner table assigned to t gets garbage collected, it prints a message prior to being collected. Likewise for the outer table when reaching the end of script:

local meta =
{
    __gc = function(self)
        print("destroying self: " .. self.name)
    end
}

local t = setmetatable({ name = "outer" }, meta)
do
    local t = { name = "inner" }
    setmetatable(t, meta)
end