• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

先看一段简单的代码:

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...这样的顺序遍历,保证顺序,不保证遍历完全;

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
cocos2d-xc++导出lua发布时间:2022-07-22
下一篇:
[Golang]lua战斗验证服务器发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap