Lua中的'for in'循环调用功能是否正常?

时间:2014-01-12 11:36:11

标签: 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隐式调用函数迭代器:   我(s)

任何人都可以告诉我,发生了什么?

1 个答案:

答案 0 :(得分:2)

是。引用Lua Manual

  

泛型for语句适用于函数,称为迭代器。在每次迭代时,调用迭代器函数以生成新值,在此新值为nil时停止。

泛型for语句只是一种语法糖:

  

这样的for语句
for var_1, ···, var_n in explist do block end
     

等同于代码:

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