迭代器
迭代器就是一层一层的往下累加的过程,可以看做是C++中的static的过程,或者说是遍历结合的一种方式;
//定义迭代器函数
function iteraFunction(tTable)
local i = 0
return function()
//调用函数外部的变量 每次都会保存之前的状态 一种累加的状态
i = i + 1
return tTable[i]
end
end
local tTmp = {10, 20, 30, 40}
//在这里iter就是代替了iteraFunction(tTable)函数 type(iter) = function; //type(iter()) = number;
local iter = iteraFunction(tTmp)
while(1) do
local value = iter()
if value == nil then
break
end
print(value)
end
//输出的值:10, 20, 30, 40
其实 刚才的迭代器还可以这样用
for value in iteraFunction(tTmp) do
print(value)
end