注意:叠待值遇到nil就退出
叠代器,是符合for遍历框架,需要满足条件
1-叠代函数,常量,控制变量
2-叠代函数可以接受二个参数,当然也可以忽略处理(利用闭包封装参数作为控制变量和状态变量)
无状态示例
function iter (a,i)
? ? i = i + 1
? ? local v = a[i]
? ? if v then
? ? ? ?return i,v
? ? end
end
?
function ipairs (a)
? ? return iter,a,0
end
多状态示例
array = {"Google","Runoob"}
function elementIterator (collection)
? ?local index = 0
? ?local count = #collection
? ?-- 闭包函数
? ?return function ()
? ? ? index = index + 1
? ? ? if index <= count
? ? ? then
? ? ? ? ?-- ?返回迭代器的当前元素
? ? ? ? ?return collection[index]
? ? ? end
? ?end
end
for element in elementIterator(array)
do
? ?print(element)
end