0Pricing
Lua Academy · Lesson

Coroutine-Based Generators

Use coroutine.wrap to create lazy generator sequences.

Coroutine-Based Generators is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Motivation for Coroutine Generators

Closures work well for simple generators. But if the generation logic requires nested loops or complex control flow, a coroutine generator is much cleaner.

coroutine.wrap Basics

coroutine.wrap(fn) returns a function. Each call resumes the coroutine; values yielded via coroutine.yield become the return value.

local gen = coroutine.wrap(function()
  coroutine.yield(1)
  coroutine.yield(2)
  coroutine.yield(3)
end)
for v in gen do print(v) end

Infinite Sequence Generator

A coroutine can yield indefinitely, making it perfect for infinite sequences terminated by the caller with break.

local function naturals()
  return coroutine.wrap(function()
    local n = 0
    while true do
      n = n + 1
      coroutine.yield(n)
    end
  end)
end
for v in naturals() do
  if v > 5 then break end
  print(v)
end

Tree Traversal Generator

Recursive deep traversal is trivial with coroutines — just yield from recursive calls without managing an explicit stack.

local function walkTree(node)
  return coroutine.wrap(function()
    local function recurse(n)
      coroutine.yield(n.value)
      for _, child in ipairs(n.children or {}) do
        recurse(child)
      end
    end
    recurse(node)
  end)
end

Fibonacci Generator

The Fibonacci sequence is natural as a coroutine: keep two state variables and yield each term.

local function fibs()
  return coroutine.wrap(function()
    local a, b = 0, 1
    while true do
      coroutine.yield(a)
      a, b = b, a + b
    end
  end)
end
local fib = fibs()
for i = 1, 8 do print(fib()) end

Passing Values into the Generator

The argument to the resumed function is the return value of yield, enabling two-way communication.

local acc = coroutine.wrap(function()
  local total = 0
  while true do
    local n = coroutine.yield(total)
    total = total + (n or 0)
  end
end)
acc()  -- start
print(acc(10))  -- 10
print(acc(5))   -- 15

coroutine.wrap vs coroutine.create

wrap is simpler and throws on error. create returns a thread object and lets you handle errors from resume's return values.

Generator Pipeline

Chain coroutine-based generators for lazy pipelines: producer yields raw data, filter yields matching items, map yields transformed items.

Error Propagation

If a wrapped coroutine throws an error, the wrap-function also throws. Wrap the generator call in pcall for safe consumption.

Memory Efficiency

Coroutine generators are lazy — they compute values on demand. This avoids building large intermediate tables, a major advantage for large datasets.

Exhaustion Handling

When the coroutine function returns (not yields), the next call to the wrapped function returns nil, naturally terminating a generic for loop.

Coroutine Generator Question

What happens when a coroutine.wrap-based generator's coroutine function returns (not yields)?

Recap: Coroutine Generators

coroutine.wrap turns any coroutine into a reusable generator function. It enables lazy infinite sequences, recursive traversals, and pipeline stages with clean control flow.

Frequently asked questions

Is the “Coroutine-Based Generators” lesson free?

Yes — the full text of “Coroutine-Based Generators” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Coroutine-Based Generators”?

Use coroutine.wrap to create lazy generator sequences. 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; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Coroutine-Based Generators” 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

  1. The Generic for Protocol
  2. Stateless Iterators
  3. Stateful Iterators with Closures
  4. Coroutine-Based Generators
← Back to Lua Academy