关于lua闭包的一个小问题

array = {"Lua", "Tutorial"}

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

我比较不理解的就是:迭代函数elementIterator闭包返回了一个匿名函数,被赋到了element上,按理来说element应该是个函数,为什么这里直接输出函数本身就执行了,不是应该加个括号才执行吗?
开满天机
浏览 749回答 2
2回答

慕仙森

应该是属于符合手册规定的迭代器写法这里elementIterator是迭代工厂,相当于一个提供状态的对象返回的function()闭包是才是迭代器,返回每个值而for或while直接在使用迭代器返回每个值,所以element不会等同于迭代器函数而是各个值..
打开App,查看更多内容
随时随地看视频慕课网APP