Lua Weak Tables and GC
Lua manages memory automatically with a garbage collector (GC). You create tables, strings and closures freely, and when no part of the program can reach a value anymore, the collector frees its memory. You never call free. This lesson explains how that works in practice, and how weak tables let you hold references that don't keep objects alive.
Reachability
A value stays alive as long as it is reachable: from a global, from a local on the stack, from an upvalue, or from inside another reachable table. Once the last reference is gone, the value is garbage:
local registry = {}
local function makePlayer(name)
local p = { name = name }
registry[#registry + 1] = p -- the registry keeps a reference
return p
end
local hero = makePlayer("Ash")
hero = nil -- our variable no longer refers to it ...
collectgarbage() -- ... but the registry still does
print(#registry, registry[1].name)1 Ash
This is the most common "memory leak" in Lua programs: an object you consider finished is still stored in some cache or list.
Weak tables
A table's metatable can have a __mode field that makes its references weak, meaning they don't count for reachability:
__mode |
Weak part | Entry disappears when… |
|---|---|---|
"k" |
keys | the key object is collected |
"v" |
values | the value object is collected |
"kv" |
both | either is collected |
local cache = setmetatable({}, { __mode = "v" })
do
local temp = { data = "big texture" }
cache.texture = temp
cache.config = { volume = 7 } -- referenced only by the cache
print(cache.texture ~= nil, cache.config ~= nil)
collectgarbage()
print("inside block:", cache.texture ~= nil, cache.config ~= nil)
end
collectgarbage() -- temp is out of scope now
print("after block:", cache.texture, cache.config)true true
inside block: true false
after block: nil nil
The table { volume = 7 } was only referenced by the weak cache, so the first collection removed it. temp survived while the local variable was in scope.
Note: Only objects (tables, functions, coroutines, userdata) are removed from weak tables. Strings, numbers and booleans are values, not collectable objects in this sense, and stay.
Weak keys: attaching data to objects
Weak keys let you associate extra data with objects you don't own, without keeping them alive. This is how many libraries store "private" fields:
local extra = setmetatable({}, { __mode = "k" })
local function tag(obj, label) extra[obj] = label end
local a, b = {}, {}
tag(a, "first"); tag(b, "second")
local function countEntries(t)
local n = 0
for _ in pairs(t) do n = n + 1 end
return n
end
print(countEntries(extra))
b = nil
collectgarbage()
print(countEntries(extra), extra[a])2
1 first
Memoisation with a weak cache
A cache keyed by objects should not stop those objects from being freed:
local areaCache = setmetatable({}, { __mode = "k" })
local computed = 0
local function area(rect)
local cached = areaCache[rect]
if cached then return cached end
computed = computed + 1
local a = rect.w * rect.h
areaCache[rect] = a
return a
end
local r = { w = 4, h = 5 }
print(area(r), area(r), "computed " .. computed .. "x")20 20 computed 1x
Finalizers: __gc
A __gc metamethod runs when the collector frees a table. It is meant for releasing external resources (a file handle, a GPU texture); don't rely on its timing for program logic:
local function resource(name)
return setmetatable({ name = name }, {
__gc = function(r) print("finalizing " .. r.name) end,
})
end
do
local r = resource("socket#1")
end
print("before collect")
collectgarbage()
print("after collect")before collect
finalizing socket#1
after collect
For deterministic cleanup, prefer <close> variables (error handling lesson).
Controlling the collector
collectgarbage(opt) talks to the GC:
| Call | Effect |
|---|---|
collectgarbage() / "collect" |
run a full collection now |
"count" |
memory in use, in kilobytes |
"step" |
do a small step of incremental work |
"stop" / "restart" |
pause / resume automatic collection |
"incremental" / "generational" |
choose the collection mode (5.4) |
"isrunning" |
is the collector running? |
print(collectgarbage("isrunning"))
collectgarbage("stop")
print(collectgarbage("isrunning"))
collectgarbage("restart")
print(collectgarbage("isrunning"))
collectgarbage("generational") -- switch modes
print(collectgarbage("incremental")) -- returns the previous modetrue
false
true
generational
Lua 5.4's generational mode assumes most objects die young (true for many games and servers) and can reduce GC time. The exact amount of memory used ("count") varies between builds and runs, so it isn't printed here.
Test yourself
When can Lua's garbage collector free a table?
- When you call
free(t) - When no reachable variable or table refers to it
- After 60 seconds
- When the program ends only
What does __mode = "k" do?
- Makes the table read-only
- Makes the keys weak, so key objects can be collected
- Sorts the keys
- Makes keys case-insensitive
Which values are never removed from a weak table?
- Tables
- Functions
- Strings and numbers
- Coroutines