Lua 5.3 迭代器的简单示例
创建”closure”模式的”iterator”
function allowrds()
local line = io.read()
local pos =
return function ()
while line do
local s, e = string.find(line, "%w+", pos)
if s then
pos = e +
return string.sub(line, s, e)
else
line = io.read()
pos =
end
end
return nil
end
end for word in allowrds() do
print(word)
end
结果运行现象:
创建”complex state iterator”模式的”iterator”
function iter(state)
while state.line do
local s, e = string.find(state.line, "%w+", state.pos)
if s then
state.pos = e +
return string.sub(state.line, s, e)
else
state.line = io.read()
state.pos =
end
end
return nil
end function allowrds()
local state = {line = io.read(), pos = }
return iter, state
end for word in allowrds() do
print(word)
end
结果运行现象: