Lua笔记(23)—— pairs和ipairs

在这篇帖子中,提到pairsipairs的区别:

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,返回的keyvalue没有什么顺序。而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是数字的元素。