国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > 綜合 > 正文

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

2024-07-21 23:04:12
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

官方文檔上的說(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è)例子

 

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

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)不輸出任何值。

 

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

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

 

那么,如果是

 

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

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

 

則會(huì)輸出所有:

 

復(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é)果顯而易見(jiàn)就是key=1時(shí)的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時(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 

 

Lua,pairs,ipairs,區(qū)別

Lua,pairs,ipairs,區(qū)別

 
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 万年县| 民乐县| 增城市| 乌恰县| 寿宁县| 获嘉县| 泾川县| 万源市| 彭水| 潜山县| 岳阳市| 荆州市| 淮滨县| 湖南省| 双江| 霍山县| 伊通| 乌拉特前旗| 丰县| 万源市| 台东县| 武汉市| 三原县| 阳曲县| 曲阜市| 贡觉县| 乌拉特中旗| 永新县| 濮阳县| 车险| 行唐县| 兰西县| 大城县| 慈溪市| 扬州市| 阿坝县| 肃北| 佛学| 安吉县| 泸溪县| 慈利县|