Lua中的'for in'循环是否调用函数?

3

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”循环隐式地使用状态参数调用迭代器函数 i(s)。有人能告诉我发生了什么吗?

正确使用上述迭代器的方式是:for i in allwords() do print(i) end - lbaby
1个回答

3

是的。引用Lua手册

通用的for语句适用于被称为迭代器的函数。在每次迭代中,都会调用迭代器函数来产生一个新值,当此新值为nil时停止。

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

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

这很有意义。谢谢! - lbaby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接