简介
标准库提供了集中迭代器,包括迭代文件每行的io.lines
,迭代table元素的pairs
,迭代数组元素的ipairs
,迭代字符串中单词的string.gmatch
等等。LUA手册中对与pairs
,ipairs
解释如下:
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 pairs (1,t1), (2,t2), ···, up to the first integer key absent from the table.
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.
说明
这样就可以看出 ipairs
以及pairs
的不同。
pairs
可以遍历表中所有的key
,并且除了
迭代器本身以及遍历表本身还可以返回nil
;
但是ipairs
则不能返回nil
,只能返回数字0
,如果遇到nil则退出
。它只能遍历到表中出现的第一个不是整数的key
pairs 为显示所有的,而 ipairs 则是如果碰到 nil 则退出。
例题说明
local tabFiles = {
[3] = "Hello",
[6] = "I'm",
[4] = "Sollyu"
}
for k, v in ipairs(tabFiles) do
print(k, v)
end
根据刚才的分析,它在 ipairs(tabFiles)
遍历中,当key=1
时候value=nil
,所以直接跳出循环不输出任何值
。
那么,如果是
for k, v in pairs(tabFiles) do
print(k, v)
end
则会输出所有
现在改变一下表内容
local tabFiles = {
[1] = "Hello",
[6] = "I'm",
[4] = "Sollyu"
}
-- 这里是 ipairs
for k, v in ipairs(tabFiles) do
print(k, v)
end
现在的输出结果显而易见就是key=1
时的value=test1