Finalizers with __gc
Register __gc metamethods for cleanup when objects are collected.
What Is a Finalizer?
A finalizer is a function called by the GC just before an object is freed. In Lua, it is implemented via the __gc metamethod on a table's metatable.
Setting a Finalizer
Attach a __gc function to a metatable before or when the object is created.
local mt = {
__gc = function(self)
print("Finalizing:", self.name)
end
}
do
local obj = setmetatable({name = "resource"}, mt)
end
collectgarbage() -- prints: Finalizing: resourceAll lessons in this course
- Lua Garbage Collector Basics
- Weak Keys and Weak Values
- Finalizers with __gc
- Avoiding Memory Leaks