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) endAll lessons in this course
- The Generic for Protocol
- Stateless Iterators
- Stateful Iterators with Closures
- Coroutine-Based Generators