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 關注
- 626 瀏覽
添加回答
舉報
0/150
提交
取消