亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Lua 中 pairs 和 ipairs 的區(qū)別

 更新時間:2014年09月29日 10:01:45   投稿:junjie  
這篇文章主要介紹了Lua 中 pairs 和 ipairs 的區(qū)別,本文用官方文檔和代碼實例總結(jié)了它的們的區(qū)別,需要的朋友可以參考下

官方文檔上的說明:

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,只能返回數(shù)字0,如果遇到nil則退出。它只能遍歷到表中出現(xiàn)的第一個不是整數(shù)的key

下面舉個例子

復(fù)制代碼 代碼如下:

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

猜測它的輸出結(jié)果是什么呢?根據(jù)剛才的分析,它在 ipairs(tabFiles) 遍歷中,當key=1時候value就是nil,所以直接跳出循環(huán)不輸出任何值。

復(fù)制代碼 代碼如下:

>lua -e "io.stdout:setvbuf 'no'" "test.lua" 
>Exit code: 0 

那么,如果是

復(fù)制代碼 代碼如下:

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

則會輸出所有:

復(fù)制代碼 代碼如下:

>lua -e "io.stdout:setvbuf 'no'" "test.lua"   
3 test2  
6 test3  
4 test1  
>Exit code: 0 

現(xiàn)在改變一下表內(nèi)容:

復(fù)制代碼 代碼如下:

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

現(xiàn)在的輸出結(jié)果顯而易見就是key=1時的value值test1

復(fù)制代碼 代碼如下:

>lua -e "io.stdout:setvbuf 'no'" "test.lua"   
1 test1  
>Exit code: 0 

復(fù)制代碼 代碼如下:

-- [[示例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時斷開  
    print( tt[i] )  
end  
 
-- [[示例2.]] --  
tbl = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}  
 
for i,v in ipairs(tbl) do    --輸出前三個  
    print( tbl[i] )  
end  
 
for i,v in pairs(tbl) do    --全部輸出  
    print( tbl[i] )  
end 

相關(guān)文章

最新評論