-- yield hands one value out and pauses the body
local function counter(low, high, step)
return coroutine.wrap(function()
for current = low, high, step do
coroutine.yield(current)
end
end)
end
-- One value per turn, made on demand
for number in counter(3, 9, 2) do
print("number = " .. number)
end
-- No end condition: it never finishes by itself
local function powers_of_two()
return coroutine.wrap(function()
local current = 1
while true do
coroutine.yield(current)
current = current * 2
end
end)
end
-- Take exactly five from the endless generator
local next_power = powers_of_two()
local first_five = {}
for i = 1, 5 do
first_five[i] = next_power()
end
-- first_five = 1, 2, 4, 8, 16
print("first_five = "
.. table.concat(first_five, ", "))