0Pricing
Lua Academy · Lesson

Finalizers with __gc

Register __gc metamethods for cleanup when objects are collected.

Finalizers with __gc is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Resource Cleanup Pattern

Finalizers are ideal for releasing external resources: file handles, database connections, or C memory.

local function openResource(path)
  local f = io.open(path, "r")
  return setmetatable({handle = f, path = path}, {
    __gc = function(self)
      if self.handle then
        self.handle:close()
        print("Closed:", self.path)
      end
    end
  })
end

Finalizer Order

Objects with finalizers are collected in reverse order of their creation. Finalizers run one per GC cycle by default.

Resurrection

If a finalizer stores a reference to the object (in a global or upvalue), the object is resurrected. It will only get one more finalizer call when finally collected.

Userdata and __gc

In C extensions, __gc on userdata is the primary way to free C memory. For pure Lua code, tables use the same mechanism via metatables.

Proxy Objects for RAII

Create a proxy table whose __gc closes the real resource. This mimics RAII from C++.

local function scoped(resource, cleanup)
  return setmetatable({resource}, {
    __gc = function(self) cleanup(self[1]) end
  })
end

Finalizer Limitations

Finalizers should not: call coroutine operations, yield, or assume any ordering of other objects being alive. Keep them simple and short.

Weak Tables and Finalizers

Objects in weak tables can still be finalized. After finalization (and possible resurrection), they are fully collected on the next cycle.

toLua Finalizer Guard

Use a boolean flag inside the finalizer to prevent double-cleanup in case of resurrection.

local mt = {}
mt.__gc = function(self)
  if not self._closed then
    self._closed = true
    -- cleanup...
  end
end

Practical Advice

Prefer explicit :close() or :destroy() methods for deterministic cleanup. Use __gc as a safety net for accidental omissions, not as primary resource management.

Finalizer Question

When is the __gc metamethod called?

Recap: Finalizers with __gc

The __gc metamethod runs just before an object is collected, enabling RAII-style resource cleanup. Use it as a safety net; prefer explicit close/destroy methods for deterministic resource management.

Frequently asked questions

Is the “Finalizers with __gc” lesson free?

Yes — the full text of “Finalizers with __gc” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Finalizers with __gc”?

Register __gc metamethods for cleanup when objects are collected. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Finalizers with __gc” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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