close

最近在寫Lua發現pairs跟ipairs因為太像了,所以使用上可能會誤用。紀錄一下兩者的差異吧。

先看官方manual的內容
http://www.lua.org/manual/5.2/manual.html#pdf-pairs

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.


http://www.lua.org/manual/5.2/manual.html#pdf-ipairs

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.


測試一:
test = { 
    [1] = "Andy", 
    [2] = "Bob", 
    [3] = "Carlos", 
    [4] = "Denny",
    [5] = "Eric", 
}
    
    for key, value in pairs(test) do 
        print(key, value) 
    end

print ("----------pairs vs ipairs----------")

    for key, value in ipairs(test) do 
        print(key, value) 
    end

輸出結果:
2 Bob
3 Carlos
1 Andy
4 Denny
5 Eric
----------pairs vs ipairs----------
1 Andy
2 Bob
3 Carlos
4 Denny
5 Eric

結語:
pairs輸出的結果不會按照順序輸出,ipairs輸出會按照順序輸出。

測試二:
test2 = { 
    [1] = "Andy", 
    [2] = "Bob", 
    [4] = "Denny",
    [5] = "Eric", 
    word = "word",
    pi = 3.14,
}
    
    for key, value in pairs(test2) do 
        print(key, value) 
    end

print ("----------pairs vs ipairs----------")

    for key, value in ipairs(test2) do 
        print(key, value) 
    end 

輸出結果:
2 Bob
pi 3.14
1 Andy
4 Denny
5 Eric
word word
----------pairs vs ipairs----------
1 Andy
2 Bob

結語:
pairs輸出的結果會將內容全部輸出,ipairs輸出只會key=1開始輸出,若key+1=nil則不再輸出。


Ref:
http://www.lua.org/manual/5.2/manual.html

 

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.

arrow
arrow
    全站熱搜

    emilykevin 發表在 痞客邦 留言(0) 人氣()