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
thas a metamethod__pairs, calls it withtas argument and returns the first three results from the call.Otherwise, returns three values: the
nextfunction, the tablet, and nil, so that the constructionfor k,v in pairs(t) do body endwill iterate over all key–value pairs of table
t.See function
nextfor the caveats of modifying the table during its traversal.
- 如果table 含有元方法__pairs,返回它的前三个结果;
- 否则,返回函数next,table,nil;
- 会迭代table中所以键值对;
ipairs (t)
Returns three values (an iterator function, the table
t, and 0) so that the constructionfor i,v in ipairs(t) do body endwill iterate over the key–value pairs (
1,t[1]), (2,t[2]), ..., up to the first nil value.
- 返回一个迭代器函数,table,0;
- 会从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,直接跳出;
所以:
- 使用pairs(t)会遍历所以key-value,但是它是无序的(不保证按照table元素的列举顺序遍历,和key的哈希值有关);
- 使用ipairs(t)会从key=1,2,3...这样的顺序遍历,保证顺序,不保证遍历完全;
所以要根据不同的需求,使用不同的方法。

浙公网安备 33010602011771号