Reputation: 2588
There is a piece of code confuses me in Programming in Lua
local iterator -- to be defined later
function allwords ()
local state = {line = io.read(), pos = 1}
return iterator, state
end
function iterator (state)
while state.line do -- repeat while there are lines
-- search for next word
local s, e = string.find(state.line, "%w+", state.pos)
if s then -- found a word?
-- update next position (after this word)
state.pos = e + 1
return string.sub(state.line, s, e)
else -- word not found
state.line = io.read() -- try next line...
state.pos = 1 -- ... from first position
end
end
return nil -- no more lines: end loop
end
--here is the way I use this iterator:
for i ,s in allwords() do
print (i)
end
It seems that the 'for in ' loop call the function iterator implicitly with argument state: i(s)
Anyone can tell me ,what happened?
Upvotes: 3
Views: 2092
Reputation: 122383
Yes. Quoting Lua Manual
The generic
for
statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value isnil
.
The generic for
statement is just a syntax sugar:
A for statement like
for var_1, ···, var_n in explist do block end
is equivalent to the code:
do local f, s, var = explist while true do local var_1, ···, var_n = f(s, var) if var_1 == nil then break end var = var_1 block end end
Upvotes: 3