Lua中ipairs()和pairs()的區別與使用


關於ipairs()和pairs(),Lua官方手冊是這樣說明的:

pairs (t)

If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.

Otherwise, 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 (t)

If t has a metamethod __ipairs, calls it with t as argument and returns the first three results from the call.

Otherwise, 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會遍歷表中所有的key-value值,而pairs會根據key的數值從1開始加1遞增遍歷對應的table[i]值,直到出現第一個不是按1遞增的數值時候退出。

下面我們以例子說明一下吧

stars = {[1] = "Sun", [2] = "Moon", [5] = 'Earth'}

for i, v in pairs(stars) do

   print(i, v)

end

使用pairs()將會遍歷表中所有的數據,輸出結果是:

1    Sun
2    Moon
5    Earth

如果使用ipairs()的話,

for i, v in ipairs(stars) do

   print(i, v)

end

當i的值遍歷到第三個元素時,i的值為5,此時i並不是上一個次i值(2)的+1遞增,所以遍歷結束,結果則會是:

1    Sun
2    Moon

ipairs()和pairs()的區別就是這么簡單。

還有一個要注意的是pairs()的一個問題,用pairs()遍歷是[key]-[value]形式的表是隨機的,跟key的哈希值有關系。看以下這個例子:

stars = {[1] = "Sun", [2] = "Moon", [3] = "Earth", [4] = "Mars", [5] = "Venus"}

for i, v in pairs(stars) do

   print(i, v)

end

結果是:

2    Moon
3    Earth
1    Sun
4    Mars
5    Venus

並沒有按照其在表中的順序輸出。

但是如果是這樣定義表stars的話

stars = {"Sun", "Moon",  “Earth”, "Mars",  "Venus"}

結果則會是

1    Sun
2    Moon
3    Earth
4    Mars
5    Venus

你清楚了嗎?:)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM