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,t[1]
), (2,t[2]
), ···, 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
.
如:
website= {"www.baidu.com", "www.google.com", ["baidu"] = "www.baidu.com", ["google"] = "www.google.com"}
for key, value in ipairs(website) do
print(key, value)
end
-pairs()函数基本和ipairs()函数用法相同, 区别在于:
pairs()可以遍历整个table,即包括数组及非数组部分。
-->如有pairs迭代输出如下:
-->1 www.baidu.com
-->2 www.google.com
-->baidu www.baidu.com
-->google www.google.com
ipairs()函数用于遍历table中的数组部分。
-->如有ipairs迭代输出如下:
-->1 www.baidu.com
-->2 www.google.com