Lua中ipair和pair的區(qū)別
先看看官方手冊(cè)的說(shuō)明吧:
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.
原來(lái),pairs會(huì)遍歷table的所有鍵值對(duì)。如果你看過(guò)耗子叔的Lua簡(jiǎn)明教程,你知道table就是鍵值對(duì)的數(shù)據(jù)結(jié)構(gòu)。
而ipairs就是固定地從key值1開(kāi)始,下次key累加1進(jìn)行遍歷,如果key對(duì)應(yīng)的value不存在,就停止遍歷。順便說(shuō)下,記憶也很簡(jiǎn)單,帶i的就是根據(jù)integer key值從1開(kāi)始遍歷的。
請(qǐng)看個(gè)例子。
tb = {"oh", [3] = "god", "my", [5] = "hello", [6] = "world"}
for k,v in ipairs(tb) do
print(k, v)
end
輸出結(jié)果就是:
1 oh
2 my
3 god
因?yàn)閠b不存在tb[4],所以遍歷到此為止了。
for k,v in pairs(tb) do
print(k, v)
end
輸出結(jié)果:
1 oh
2 my
3 god
6 world
5 hello
我們都能猜到,將輸出所有的內(nèi)容。然而你發(fā)現(xiàn)輸出的順序跟你tb中的順序不同。
如果我們要按順序輸出怎么辦?辦法之一是:
for i = 1, #tb do
if tb[i] then
print(tb[i])
else
end
當(dāng)然,僅僅是個(gè)數(shù)組的話(huà),ipairs也沒(méi)問(wèn)題。
以上(為什么不少回答會(huì)以「以上」收尾?,這里就是結(jié)束的意思吧)
相關(guān)文章
Lua進(jìn)階教程之閉包函數(shù)、元表實(shí)例介紹
這篇文章主要介紹了Lua進(jìn)階教程之閉包函數(shù)、元表實(shí)例介紹,本文詳細(xì)講解了Lua的閉包函數(shù)和元表,并同時(shí)和C++做了比較,需要的朋友可以參考下2014-09-09Lua的迭代器使用中應(yīng)該避免的問(wèn)題和技巧
這篇文章主要介紹了Lua的迭代器使用中應(yīng)該避免的問(wèn)題和技巧,本文介紹了避免創(chuàng)建閉合函數(shù)、利用恒定狀態(tài)創(chuàng)造更多變量、不需要for循環(huán)的迭代器等內(nèi)容,需要的朋友可以參考下2014-09-09Lua中的迭代器和泛型for學(xué)習(xí)總結(jié)
這篇文章主要介紹了Lua中的迭代器和泛型for學(xué)習(xí)總結(jié),本文講解了迭代器和泛型for的基礎(chǔ)知識(shí)、泛型for的語(yǔ)義、無(wú)狀態(tài)的迭代器等內(nèi)容,需要的朋友可以參考下2014-09-09Lua的table庫(kù)函數(shù)insert、remove、concat、sort詳細(xì)介紹
這篇文章主要介紹了Lua的table庫(kù)函數(shù)insert、remove、concat、sort詳細(xì)介紹,本文分別給出了這幾個(gè)函數(shù)的使用實(shí)例,需要的朋友可以參考下2015-04-04