array = {"Lua", "Tutorial"}function elementIterator (collection)local index = 0local count = #collection-- 闭包函数return function ()index = index + 1if index <= countthen-- 返回迭代器的当前元素return collection[index]endendendfor element in elementIterator(array)doprint(element)end我比较不理解的就是:迭代函数elementIterator闭包返回了一个匿名函数,被赋到了element上,按理来说element应该是个函数,为什么这里直接输出函数本身就执行了,不是应该加个括号才执行吗?
2 回答

智慧大石
TA贡献1946条经验 获得超3个赞
应该是属于符合手册规定的迭代器写法
这里elementIterator是迭代工厂,相当于一个提供状态的对象
返回的function()闭包是才是迭代器,返回每个值
而for或while直接在使用迭代器返回每个值,所以element不会等同于迭代器函数而是各个值..
- 2 回答
- 0 关注
- 599 浏览
添加回答
举报
0/150
提交
取消