Generators
A generator uses a coroutine to produce a sequence of values one at a time.
In this page:
Generators
A generator is a function that yields successive values, and wrapping it in coroutine.wrap gives an iterator usable in a for loop. Values are produced lazily, only when the loop asks for the next one. This works even for infinite sequences, as long as the loop stops on its own.
Note:
A for loop stops when the iterator returns nil, so a finished generator ends the loop.
Example: Generators
local function range(n)
return coroutine.wrap(function()
for i = 1, n do coroutine.yield(i) end
end)
end
for v in range(4) do io.write(v, " ") end
print()
local function fib()
return coroutine.wrap(function()
local a, b = 0, 1
while true do
coroutine.yield(a)
a, b = b, a + b
end
end)
end
for v in fib() do
if v > 50 then break end
io.write(v, " ")
end
print()
-- Output:
-- 1 2 3 4
-- 0 1 1 2 3 5 8 13 21 34
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Building the whole list first instead of yielding
- Writing an infinite generator without a break
- Calling the generator function instead of using its result
Chapter Summary
- Yield values one by one
- wrap turns it into an iterator
- Values are produced lazily
- The loop ends when the function returns nil
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: