Lua 中 pairs 和 ipairs 的区别

(编辑:jimmy 日期: 2024/10/5 浏览:2)

官方文档上的说明:

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,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key

下面举个例子

复制代码 代码如下:
local tabFiles = {  
[3] = "test2",  
[6] = "test3",  
[4] = "test1" 
}  
for k, v in ipairs(tabFiles) do 
    print(k, v)  
end 

猜测它的输出结果是什么呢?根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。

复制代码 代码如下:
>lua -e "io.stdout:setvbuf 'no'" "test.lua" 
>Exit code: 0 

那么,如果是

复制代码 代码如下:
for k, v in pairs(tabFiles) do 
    print(k, v)  
end 

则会输出所有:

复制代码 代码如下:
>lua -e "io.stdout:setvbuf 'no'" "test.lua"   
3 test2  
6 test3  
4 test1  
>Exit code: 0 

现在改变一下表内容:

复制代码 代码如下:
local tabFiles = {  
[1] = "test1",  
[6] = "test2",  
[4] = "test3" 
}  
 
for k, v in ipairs(tabFiles) do 
    print(k, v)  
end 

现在的输出结果显而易见就是key=1时的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时断开  
    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 

Lua 中 pairs 和 ipairs 的区别

Lua 中 pairs 和 ipairs 的区别

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。