-- yield 交出一个值,并暂停函数体
local function counter(low, high, step)
return coroutine.wrap(function()
for current = low, high, step do
coroutine.yield(current)
end
end)
end
-- 每次循环一个值,按需生成
for number in counter(3, 9, 2) do
print("number = " .. number)
end
-- 没有结束条件:它自己永远不会结束
local function powers_of_two()
return coroutine.wrap(function()
local current = 1
while true do
coroutine.yield(current)
current = current * 2
end
end)
end
-- 从无限生成器中恰好取五个
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, ", "))