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”循环使用参数状态隐式调用函数迭代器:
是)

谁能告诉我,这是怎么回事?

最佳答案

是的。引用 Lua Manual



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

关于lua - Lua中的 'for in '循环调用函数有吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21074147/

10-15 02:45