实践为先,先写个错误代码
function iter_pro (arr,b) local index = 0 return function () index = index + 1 if arr[index] then return arr[index] end end end a={1,2,3,5,4} for v in iter_pro ,a,0 do print(v) end
首先。既然已经保存了状态,就没必要用到第2个参数
function iter_pro (arr,b)
其次,真正的迭代器为“工厂”iter_pro 生成的闭包 要调用工厂生成迭代器
for v in iter_pro ,a,0 do
正确的代码为
function iter_pro (arr) local index = 0 return function () index = index + 1 if arr[index] then return arr[index] end end end a={1,2,3,5,4} for v in iter_pro(a) do print(v) end
有状态的迭代器完成了
标签:function,状态,arr,end,迭代,index,pro,iter From: https://www.cnblogs.com/omori-Sakuya/p/17528079.html