Finalizers with __gc
Register __gc metamethods for cleanup when objects are collected.
Finalizers with __gc is a free Lua Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
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: resourceResource 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
})
endFinalizer 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
})
endFinalizer 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
endPractical 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.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Finalizers with __gc” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Finalizers with __gc”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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
- Lua Garbage Collector Basics
- Weak Keys and Weak Values
- Finalizers with __gc
- Avoiding Memory Leaks