Lua Garbage collector - the __gc metamethod



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: " ..

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