在这篇帖子中,提到pairs
和ipairs
的区别:
pairs() returns an iterator that will return the key and value of every key in the table, in no particular order. Usually, k and v are used to hold the key and value it returns. This is used to perform actions on each item in a table in turn, like when printing the contents of each value in the table.
ipairs() is very similar to pairs(), except that it will start at table[1] and iterate through all numerically indexed entries until the first nil value. It does this in order, which can be useful when you’re looking for the first item in a list that meets certain criterion.
pairs
遍历任意table
,返回的key
和value
没有什么顺序。而ipairs
只会返回key
是数字的元素。ipairs
通常用在访问数组上。
参考下面这个程序:
t = {hello = 100, 200, 300}
print("k, v in pairs:")
for k, v in pairs(t) do
print(k, v)
end
print("k, v in ipairs:")
for k, v in ipairs(t) do
print(k, v)
end
执行结果如下:
k, v in pairs:
1 200
2 300
hello 100
k, v in ipairs:
1 200
2 300
可以看到,pairs
可以遍历所有的key-value
对,而ipairs
只会访问key
是数字的元素。