码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-08-18 00:39:07      阅读:5508      评论:0      收藏:0      [点我收藏+]

标签:

 

先看一段简单的代码:

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

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

 

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

标签:

原文地址:http://www.cnblogs.com/zzya/p/5778125.html

(0)
(2)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!