使用闭包的奇数开发 迭代器,直接看源码了
-- 使用闭包 开发自己的迭代器
function Itrs(tableList)
-- 指定 upValue
local i = 0
return function()
i = i + 1
-- 输出 下标
return tableList[i]
end
end
--表的 内容可以自定义
myTable = {
10,
20,
40,
50,
39,
40,
90,
99
}
-- 迭代输出
result = Itrs(myTable)
-- 使用 while 作输出
function ShowWhileTable()
while (true) do
local j = result()
-- 如果说对象为空的话跳出
if (j == nil) then
break
end
print(j)
end
end
-- 使用 for 进行输出、
function ShowForTable()
for i in pairs(myTable) do
--for 循环中,如果有 nil 的话可以直接进行跳出
local j = result()
print(j)
end
end
ShowForTable()
最后在 VSCode 中的运行结果是这样的: