Lua 中 pairs 和 ipairs 的區(qū)別
官方文檔上的說(shuō)明:
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)的第一個(gè)不是整數(shù)的key
下面舉個(gè)例子
local tabFiles = {
[3] = "test2",
[6] = "test3",
[4] = "test1"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
猜測(cè)它的輸出結(jié)果是什么呢?根據(jù)剛才的分析,它在 ipairs(tabFiles) 遍歷中,當(dāng)key=1時(shí)候value就是nil,所以直接跳出循環(huán)不輸出任何值。
>lua -e "io.stdout:setvbuf 'no'" "test.lua"
>Exit code: 0
那么,如果是
for k, v in pairs(tabFiles) do
print(k, v)
end
則會(huì)輸出所有:
>lua -e "io.stdout:setvbuf 'no'" "test.lua"
3 test2
6 test3
4 test1
>Exit code: 0
現(xiàn)在改變一下表內(nèi)容:
local tabFiles = {
[1] = "test1",
[6] = "test2",
[4] = "test3"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
現(xiàn)在的輸出結(jié)果顯而易見(jiàn)就是key=1時(shí)的value值test1
>lua -e "io.stdout:setvbuf 'no'" "test.lua"
1 test1
>Exit code: 0
-- [[示例1.]] --
local tt =
{
[1] = "test3",
[4] = "test4",
[5] = "test5"
}
for i,v in pairs(tt) do -- 輸出 "test4" "test3" "test5"
print( tt[i] )
end
for i,v in ipairs(tt) do -- 輸出 "test3" k=2時(shí)斷開(kāi)
print( tt[i] )
end
-- [[示例2.]] --
tbl = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}
for i,v in ipairs(tbl) do --輸出前三個(gè)
print( tbl[i] )
end
for i,v in pairs(tbl) do --全部輸出
print( tbl[i] )
end
相關(guān)文章
Lua教程(一):簡(jiǎn)介、優(yōu)勢(shì)和應(yīng)用場(chǎng)景介紹
這篇文章主要介紹了Lua教程(一):簡(jiǎn)介、優(yōu)勢(shì)和應(yīng)用場(chǎng)景介紹,本文是Lua教程系列文章的第一篇,需要的朋友可以參考下2015-04-04Lua學(xué)習(xí)筆記之?dāng)?shù)據(jù)類型
這篇文章主要介紹了Lua學(xué)習(xí)筆記之?dāng)?shù)據(jù)類型,本文同時(shí)講解了開(kāi)發(fā)環(huán)境的搭建,需要的朋友可以參考下2014-09-09Lua協(xié)同程序函數(shù)coroutine使用實(shí)例
這篇文章主要介紹了Lua協(xié)同程序函數(shù)coroutine使用實(shí)例,協(xié)程是協(xié)同程序的簡(jiǎn)稱,顧名思義,就是協(xié)同工作的程序,需要的朋友可以參考下2014-09-09Lua學(xué)習(xí)筆記之函數(shù)、變長(zhǎng)參數(shù)、closure(閉包)、select等
這篇文章主要介紹了Lua學(xué)習(xí)筆記之函數(shù)、變長(zhǎng)參數(shù)、closure(閉包)、select等,本文著重講解了這些特性的用法,并給出代碼實(shí)例,需要的朋友可以參考下2015-04-04Lua中的元表(metatable)、元方法(metamethod)詳解
這篇文章主要介紹了Lua中的元表(metatable)、元方法(metamethod)詳解,本文對(duì)它做了詳細(xì)講解,并給出實(shí)例來(lái)說(shuō)明,需要的朋友可以參考下2014-09-09