标准库提供了集中迭代器,包括迭代文件每行的(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.
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,以此类推。若显示写出的下标'[]'和非显示写出的有冲突,则忽略显示下标的值。