lua中pairs 和 ipairs区别

Lua中的pairs遍历表中全部key-value对,而ipairs从1开始递增遍历数组部分。pairs不受下标顺序限制,ipairs则按顺序且只适用于下标连续的数组。对于非连续或非从1开始的下标,ipairs可能无法遍历完整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的 

(string.gmatch)等等。LUA手册中对与pairs,ipairs解释如下:

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(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遍历表中全部key,value
ipairs从下标为1开始遍历,然后下标累加1,如果某个下标元素不存在就终止遍历。这就导致如果下标不连续或者不是从1开始的表就会中断或者遍历不到元素。

print('-------------------');
a={1,nil,3,nil,5,6,7,8}
b={[-4]=-4,1,[1]=9,2,3,[4]=4}
for i,v in pairs(a) do
	print("key = ",i,"value =",v)
end
print('-------------------');
for i,v in ipairs(a) do
	print("key = ",i,"value =",v)
end
print('-------------------');
for i,v in pairs(b) do
	print("key = ",i,"value =",v)
end
print('-------------------');
for i,v in ipairs(b) do
	print("key = ",i,"value =",v)
end
print('-------------------');


结果是:

-------------------
key = 1 value = 1
key = 3 value = 3
key = 5 value = 5
key = 6 value = 6
key = 7 value = 7
key = 8 value = 8
-------------------
key = 1 value = 1
-------------------
key = 1 value = 1
key = 2 value = 2
key = 3 value = 3
key = -4 value = -4
key = 4 value = 4
-------------------
key = 1 value = 1
key = 2 value = 2
key = 3 value = 3
key = 4 value = 4
-------------------

可以知道

1.pairs若全部没有显示写出'[]'下标,则会按照下标从小到大遍历所有非nil值,否则将按照随机下标遍历所有非nil值。

2.ipairs是默认第一个非显示写出'[]'为下标1,以此类推。若显示写出的下标'[]'和非显示写出的有冲突,则忽略显示下标的值。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值