lua ipairs(t) and pairs(t)

ipairs(t) and pairs(t)

reference:html

http://www.lua.org/manual/5.3/manual.html函數

ipairs (t)

Returns three values (an iterator function, the table t, and 0) so that the constructionlua

for i,v in ipairs(t) do body end

will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.spa

 

 

pairs (t)

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

Otherwise, returns three values: the next function, the table t, and nil, so that the constructionhtm

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.three

See function next for the caveats of modifying the table during its traversal.ip

 

示例1:

local tabFiles = {   
[2] = "test2",  
[4] = "test3",  
[3] = "test1"  
}  
   
for k, v in ipairs(tabFiles) do  
print(k, v)  
end

運行結果:get

當 Lua 調用 ipairs(a)開始循環時,他獲取三個值:迭代函數 iter,狀態常量 a 和控制變量初現的原始方法:始值 0;而後 Lua 調用 iter(a,0)返回 1,a[1](除非 a[1]=nil);第二次迭代調用 iter(a,1)返回 2,a[2]……直到第一個非 nil 元素。it

因此在 ipairs(tabFiles) 遍歷中,當key=1時候value就是nil,因此直接跳出循環不輸出任何值。

示例2:

local tabFiles = {
[2] = "test2",
[4] = "test3",
[3] = "test1"
}

for k, v in pairs(tabFiles) do
print(k, v)
end

運行結果:

3	test1
2	test2
4	test3

疑問:

示例2輸出順序爲何是這樣的?

示例3:

local tabFiles1 = {   
[3] = "test2",  
[6] = "test3",  
[4] = "test1"  
}  
   

for k, v in pairs(tabFiles1) do  
print(k, v)  
end

運行結果:

3	test2
6	test3
4	test1

 

示例4:

local tabFiles2 = {   
[1] = "test2",  
[6] = "test3",  
[4] = "test1"  
}
for k, v in ipairs(tabFiles2) do  
print(k, v)  
end

運行結果:

1	test2

當key=2時候value就是nil,因此直接跳出循環不輸出任何值。

示例5:

local tabFiles2 = {   
[1] = "test2",  
[6] = "test3",  
[4] = "test1"  
}
for k, v in pairs(tabFiles2) do  
print(k, v)  
end

運行結果:

1	test2
6	test3
4	test1

 

示例6:

local tabFiles3 = {   
[2] = "test2",  
[6] = "test3",  
[1] = "test1",
"ok",
}  
for k, v in ipairs(tabFiles3) do
print(k, v)
end

運行結果:

1	ok
2	test2

 

示例7:

local tabFiles3 = {   
[2] = "test2",  
[6] = "test3",  
[1] = "test1",
"ok",
}  
for k, v in pairs(tabFiles3) do
print(k, v)
end
1	ok
2	test2
6	test3

註釋:

table中定義了key爲1的value,以及沒有定義key的value,發現對於key爲1的value會被沒有定義key的value覆蓋。

相關文章
相關標籤/搜索