以代码为主,辅助注释 --1.无状态迭代器 --[[ for <var-list> in <exp-list> do --staff end 其中,<exp-list>应该返回3个值:迭代器函数,恒定状态,控制变量 ]] local function getnext(list, node) if not node then return list else return node.next end end function traverse(list) return getnext, list, nil -- 返回3个值 end -------------- list = nil for i=1, 10 do list = {val = i, next = list } end for node in traverse(list) do print( node.val ) end --2.基于closure的具有状态的迭代器 local iterator function allwords() local state = {line = io.read(), pos = 1 } return iterator, state, nil end function iterator(state) while state.line do local s, e = string.find(state.line, "%w+", state.pos) if s then state.pos = e+1 return string.sub(state.line, s, e) else state.line = io.read() state.pos = 1 end end return nil end -- 使用迭代器 for word in allwords() do print( word ) end