Lua Generator: How to Build & Use Lua Code Generators

Written by

in

Lua does not have a dedicated generator keyword or yield syntax statement like Python or JavaScript. Instead, it builds generators directly on top of asymmetric coroutines and generic for loop iterators. Because Lua coroutines are full, stackful coroutines exposed through the coroutine standard library, a generator in Lua is simply a coroutine that pauses with coroutine.yield(...) and produces values on demand.


How Lua Turns Coroutines into Generators

In languages with stackless generators, yield usually only works at the top level of the generator function itself. Lua gives each coroutine its own call stack, which means you can call coroutine.yield from inside helper functions or recursive traversals—not just directly inside the main coroutine body.

Two functions in the coroutine library power most generator patterns:

  • coroutine.create(fn): Returns a thread object in a suspended state without running fn yet. You advance it manually with coroutine.resume(co, ...), which returns a boolean status flag followed by any yielded or final return values.
  • coroutine.wrap(fn): Creates a coroutine and returns a callable wrapper function instead of a thread handle. Calling that wrapper resumes the coroutine and directly returns the yielded or final values—propagating any uncaught error to the caller instead of returning false, err.

Because Lua’s generic for loop expects an iterator function as its first expression, coroutine.wrap plugs straight into for x in gen do.


Practical Examples

1. A Lazy Sequence Generator (coroutine.wrap)

A generator shines when a sequence is infinite, expensive to compute upfront, or consumed only partially. Below is a Fibonacci generator that stops as soon as the caller breaks out of the loop:

local function fib_generator(limit)
  return coroutine.wrap(function()
    local a, b = 0, 1
    while not limit or a <= limit do
      coroutine.yield(a)
      a, b = b, a + b
    end
  end)
end

for value in fib_generator(50) do
  print(value) -- 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
end

Notice there is no pre-allocated table and no manual index state outside the loop. Local variables a and b stay alive on the coroutine’s stack across each coroutine.yield(a).

2. Yielding from Inside a Recursive Helper

Because Lua coroutines preserve nested call frames, you can write natural recursive tree walkers and turn them into pull-based generators without flattening recursion into an explicit stack:

local function walk_inorder(node)
  if not node then return end
  walk_inorder(node.left)
  coroutine.yield(node.value)
  walk_inorder(node.right)
end

local function inorder_gen(root)
  return coroutine.wrap(function()
    walk_inorder(root)
  end)
end

local tree = {
  value = 2,
  left = { value = 1 },
  right = { value = 3 },
}

for v in inorder_gen(tree) do
  print(v) -- 1, 2, 3
end

3. Bidirectional Generators (Consumers / Coroutines with Input)

In Lua, coroutine.yield(...) is an expression: whatever extra arguments are passed to the next coroutine.resume(co, ...)—or to a coroutine.wrap function—become the return values of coroutine.yield. That lets a generator act as a stateful filter or accumulator receiving values pushed into it:

local running_avg = coroutine.wrap(function()
  local total, count = 0, 0
  local x = coroutine.yield() -- initial pause until first number arrives
  while x ~= nil do
    total = total + x
    count = count + 1
    x = coroutine.yield(total / count)
  end
end)

running_avg()          -- primes the coroutine up to the first yield
print(running_avg(10)) -- 10
print(running_avg(20)) -- 15
print(running_avg(30)) -- 20

Stateful Closures vs. Coroutine Generators

You do not always need a coroutine to produce a sequence. A plain closure capturing upvalues is often lighter when iteration state is trivial, while a coroutine generator is cleaner when control flow involves loops, branches, or recursion.

| Dimension | Stateful Closure Iterator | Coroutine Generator (coroutine.wrap) |
| :— | :— | :— |
| Control flow | Best for simple step counters or cursor advancement | Natural for multi-branch loops, early exits, and recursion |
| State storage | Upvalues updated on each call | Local variables and call stack across yield points |
| Overhead | Minimal—just a function closure and small state table/upvalues | Higher—allocates a coroutine thread and call stack |
| Error handling | Standard function return/error behavior | Propagates errors out of wrap and closes the coroutine in Lua 5.4 |
| Scheduler interaction | Safe if underlying calls yield to a scheduler | Be careful if code inside the generator yields to a different scheduler |


Pitfalls and Practical Notes

  • Closing abandoned coroutines in Lua 5.4: If a consumer stops early and a generator holds resources or to-be-closed variables, Lua 5.4 provides coroutine.close(co) (and coroutine.wrap automatically closes a dead/errored coroutine on failure).
  • Nested yields and schedulers: If your generator calls an async or networking layer that itself yields to an event loop, make sure you understand which resume pairs with which yield.
  • Hot inner loops: Creating a fresh coroutine on every tiny inner loop adds allocation overhead compared to a simple for i = 1, n numeric loop or a closure iterator. Reserve coroutine generators for places where clarity and lazy streaming win.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *