“for in”循环在Lua中调用函数吗?

这里有一段代码让我困惑,在 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

似乎 'for in ' 循环隐式地调用了带有参数 state 的函数 iterator:

i(s)

有人能告诉我是怎么回事吗?

点赞
用户1009479
用户1009479

是的。引用《Lua 手册》中的说法:

通用的 for 语句可用于处理被称为迭代器的函数。在每次循环时,都会调用迭代器函数以生成一个新值,当这个新值为 nil 时则停止。

通用的 for 语句只是一种语法糖:

一个类似于

for var_1, ···, var_n in explist do block end

for 语句等效于以下代码:

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
2014-01-12 12:24:44