7.1 Iterators and Closures
In Lua, we typically represent iterators by functions: each time we call the function, it returns the “next” element from the collection.
function values (t)
local i =O
return function () i = i + 1; return t[i] end
end
We can use this iterator in a while loop:
t = {10, 20, 30}
iter = values(t) -creates the iterator
while true do
local element = iter()一一calls the iterator
if element == nil then break end
print (element)
end
however, it is easier to use the generic for.
t = {10, 20, 30}
for element in values(t) do
print (element)
end
function allwords ()
local line = io.read() -- current line
local pos = 1 -- current position in the line
return function () -- iterator function
while line do -- repeat while there are lines
local s, e = string.find(line, "%w+", pos)
if s then -- found a word?
pos = e + 1 -- next position is after this word
return string.sub(line, s, e) -- return the word
else
line = io.read() -- word not found; try next line
pos = 1 -- restart from first position
end
end
return nil -- no more lines: end of traversal
end
end