-- The state lives in the closure, not in the loop
local function counter(low, high, step)
local current = low
return function()
if current > high then
return nil
end
local result = current
current = current + step
return result
end
end
-- for calls the function every turn
-- and stops at the first nil
for number in counter(3, 9, 2) do
print("number = " .. number)
end
-- A used-up iterator keeps returning nil
local next_number = counter(1, 1, 1)
local first = next_number()
-- first = 1
local second = next_number()
-- second = nil
local third = next_number()
-- third = nil
print("first = " .. first)
print("second = " .. tostring(second))
print("third = " .. tostring(third))