迭代器与closure
function allwords()
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
print("function endddddddddd")
return nil
end
end for word in allwords() do
print()
print(word)
end
无状态的迭代器
local function iter(a,i)
i=i+
local v=a[i]
if v then
return i,v
end
end
function ipairs(a)
-- return iter,a,0 --正确--for获得3个值,迭代器函数,恒定状态,以及控制变量
return iter(a,) --错误
end a={,,,}
--for k,v in ipairs(a) do
-- print(k,v)
--end for k,v in next,a do
print(k,v)
end
复杂迭代器
--复杂迭代器,不需要定义局部变量pos
local iterator
function allwords()
local state={line=io.read(),pos=}
return iterator,state
end function iterator(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 for word in allwords() do
print()
print(word)
end
真实迭代器
function allwords(f)
for line in io.lines() do
for word in string.gmatch(line,"%w+") do
f(word)
end
end
end
allwords(print)