Lua-泛型for循环 pairs和ipairs的区别

 

先看一段简单的代码:

local mytable = {
    1,
    2,
    aa = "abc",
    subtable = {},
    4,
    6
}
--for循环1
print("for --- index")
for i=1,#mytable do
    print(i)
end

--for循环2
print("for ---- index-value")
for i,v in ipairs(mytable) do
    print(i,v)
end

--for循环3
print("for ---- key-value")
for k,v in pairs(mytable) do
    print(k,v)
end

输出结果:

for --- index
1
2
3
4
for ---- index-value
1    1
2    2
3    4
4    6
for ---- key-value
1    1
2    2
3    4
4    6
subtable    table: 0x7f82d8d07660
aa    abc

3种for循环的结果各不相同,我们这里对后两种进行一下比较。 

 

 看一下,关于pairs和ipairs的定义:

pairs (t)

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

Otherwise, 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.

  1. 如果table 含有元方法__pairs,返回它的前三个结果;
  2. 否则,返回函数next,table,nil;
  3. 会迭代table中所以键值对;

 

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 key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.

  1.  返回一个迭代器函数,table,0;
  2. 会从key=1开始迭代table中的键值对,直到遇到第一个nil value;

例如:

local mytable2 = {
    [2] = "b",
    [3] = "c"
}
for i,v in ipairs(mytable2) do
    print(i,v)
end

这里什么都不会输出,当迭代key=1的键值对时,value=nil,直接跳出;

 

所以:

  1. 使用pairs(t)会遍历所以key-value,但是它是无序的(不保证按照table元素的列举顺序遍历,和key的哈希值有关);
  2. 使用ipairs(t)会从key=1,2,3...这样的顺序遍历,保证顺序,不保证遍历完全;

所以要根据不同的需求,使用不同的方法。

 

转载于:https://www.cnblogs.com/zzya/p/5778125.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值