Lua Advanced: Coroutines, Metamethods & Performance

Lesson 4 of 5

Garbage Collection & Weak Tables

Lua manages memory automatically with a garbage collector (GC), you never manually free a table, but understanding roughly how the GC decides what's collectible helps you avoid subtle memory leaks in long-running programs (like a game server that stays up for days).

How collection works, briefly

Lua's GC is a tracing collector: starting from a set of "roots" (globals, the currently running stack, etc.), it walks every reachable table/value and keeps them, anything unreachable gets freed. This means a table is eligible for collection the moment nothing still holds a reference to it, you don't need to null it out explicitly the way you might in a manual-memory language, though setting a local to nil when you're done with a large table can help it get collected sooner rather than later.

Lua

collectgarbage is rarely called manually in normal code, Lua runs the collector incrementally on its own, but it's useful when profiling memory use or right before measuring memory in a benchmark.

The leak you don't expect: caches

Lua

This looks harmless, but cache holds a strong reference to every entry forever, even after nothing else in the program cares about that user anymore. In a long-running process, this cache only grows.

Weak tables

Lua

__mode = "v" makes the table's values weak references, if nothing else in the program still holds a strong reference to a cached value, the garbage collector is free to remove that entry from cache automatically on its next pass. __mode = "k" does the same for keys, and __mode = "kv" makes both weak, useful for building a side-table that attaches extra data to objects without preventing those objects from ever being collected.

WARNING

Weak tables only help if the values themselves are collectible tables/userdata elsewhere, numbers and strings are never weakly held the way you might expect (small numbers and short strings in particular are effectively "immortal" values in Lua's implementation), so __mode = "v" won't shrink a cache whose values are plain numbers.

📝 GC & Weak Tables Quiz

Passing score: 70%
  1. 1.Setting __mode = 'v' on a table's metatable makes...

  2. 2.A table becomes eligible for garbage collection only once nothing in the program still holds a reference to it.

  3. 3.____("collect") forces Lua to run a full garbage collection cycle immediately.