0Pricing
Lua Academy · Lesson

Coroutine-Based Generators

Use coroutine.wrap to create lazy generator sequences.

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

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