← Back to Lua Course | Chapter 7: Coroutines | Lesson 5 of 7

Generators

A generator uses a coroutine to produce a sequence of values one at a time.

In this page:

  1. Generators

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

lua
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
Common Mistakes
  1. Building the whole list first instead of yielding
  2. Writing an infinite generator without a break
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.