Garbage Collector & Memory Architecture

PyLua features an automatic memory manager based on an incremental tri-color mark-and-sweep collector paired with a high-throughput Generational GC mode designed for 60+ FPS game engines.

1. The Tri-Color Mark-and-Sweep Algorithm

Memory collection in src/runtime/lgc.c categorizes all allocated heap objects (strings, tables, functions, userdata, threads) into three colors:

┌─────────────────────────┐
│     White (Unvisited)   │ ──▶ Initial state. Objects not reached during the mark phase
│                         │     are garbage and have their memory freed during sweep.
└───────────┬─────────────┘
            │ Object reached from root set (stack, globals, registry)
            ▼
┌─────────────────────────┐
│     Gray (In-Progress)  │ ──▶ Object is reachable, but its children (table keys,
│                         │     values, upvalues) have not yet been traversed.
└───────────┬─────────────┘
            │ All children scanned
            ▼
┌─────────────────────────┐
│     Black (Reachable)   │ ──▶ Object is guaranteed alive. Must never point directly
│                         │     to a White object without triggering a write barrier.
└─────────────────────────┘

2. Generational GC Mode (`LUA_GCGEN`)

Standard incremental GC scans all heap objects over multiple steps. However, in games and high-performance interactive apps, the Weak Generational Hypothesis applies: most objects die shortly after being created (temporary vectors, strings, frame tables).

In PyLua, the generational collector is enabled by default:

  • Minor Cycles: Only scan and collect young objects allocated during the current frame. Takes microsecond-level pauses with zero frame stutter!
  • Major Cycles: Run periodically to collect long-lived objects that have aged across multiple cycles.

Write Barriers (`luaC_barrier`)

If an old (survived) table is mutated to store a newly created object (e.g. oldTable.child = newObj), the VM's write barrier immediately flags the parent table as dirty, ensuring the young object is never collected prematurely.

3. Manual Garbage Collector Control (`collectgarbage`)

You can inspect and fine-tune the collector directly from PyLua scripts:

gc_control.lua
-- Get total allocated memory in kilobytes:
usedKb = collectgarbage("count")
print(string.format("Memory in use: %.2f KB", usedKb))

-- Force an immediate full garbage collection cycle:
collectgarbage("collect")

-- Temporarily stop GC during performance-critical frame sections:
collectgarbage("stop")
-- ... heavy game physics / rendering calculations ...
collectgarbage("restart")

-- Switch modes:
collectgarbage("generational")  -- Fast young-generation collection
collectgarbage("incremental")   -- Classical incremental collection