0Pricing
Lua Academy · Lesson

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: resource

All lessons in this course

  1. Lua Garbage Collector Basics
  2. Weak Keys and Weak Values
  3. Finalizers with __gc
  4. Avoiding Memory Leaks
← Back to Lua Academy