官方文檔上的說明:
ipairs (t)
Returns three values: an iterator function, the table t, and 0, so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.
pairs (t)
Returns three values: the next function, the table t, and nil, so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
這樣就可以看出 ipairs以及pairs 的不同。pairs可以遍歷表中所有的key,并且除了迭代器本身以及遍歷表本身還可以返回nil;但是ipairs則不能返回nil,只能返回?cái)?shù)字0,如果遇到nil則退出。它只能遍歷到表中出現(xiàn)的第一個不是整數(shù)的key
下面舉個例子
猜測它的輸出結(jié)果是什么呢?根據(jù)剛才的分析,它在 ipairs(tabFiles) 遍歷中,當(dāng)key=1時(shí)候value就是nil,所以直接跳出循環(huán)不輸出任何值。
那么,如果是
則會輸出所有:
現(xiàn)在改變一下表內(nèi)容:
現(xiàn)在的輸出結(jié)果顯而易見就是key=1時(shí)的value值test1
標(biāo)簽:天門 天門 濰坊 宣城 臺灣 儋州 德宏 金昌
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua 中 pairs 和 ipairs 的區(qū)別》,本文關(guān)鍵詞 Lua,中,pairs,和,ipairs,的,區(qū)別,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。