Lua中ipair和pair的區(qū)別
先看看官方手冊的說明吧:
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會遍歷table的所有鍵值對。如果你看過耗子叔的Lua簡明教程,你知道table就是鍵值對的數(shù)據(jù)結(jié)構(gòu)。
而ipairs就是固定地從key值1開始,下次key累加1進行遍歷,如果key對應(yīng)的value不存在,就停止遍歷。順便說下,記憶也很簡單,帶i的就是根據(jù)integer key值從1開始遍歷的。
請看個例子。
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
因為tb不存在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
當然,僅僅是個數(shù)組的話,ipairs也沒問題。
以上(為什么不少回答會以「以上」收尾?,這里就是結(jié)束的意思吧)
相關(guān)文章
Lua的table庫函數(shù)insert、remove、concat、sort詳細介紹
這篇文章主要介紹了Lua的table庫函數(shù)insert、remove、concat、sort詳細介紹,本文分別給出了這幾個函數(shù)的使用實例,需要的朋友可以參考下2015-04-04