简单迭代器

数组和集合 / 迭代器

-- 状态保存在闭包中,而不在循环里
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 每轮调用该函数,
-- 遇到第一个 nil 就停止
for number in counter(3, 9, 2) do
  print("number = " .. number)
end

-- 用尽的迭代器会一直返回 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))