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
.
See function next
for the caveats of modifying the table during its traversal.
从上述可以看出其区别:
pairs遍历表中全部key,value
ipairs从下标为1开始遍历,然后下标累加1,如果某个下标元素不存在就终止遍历。这就导致如果下标不连续或者不是从1开始的表就会中断或者遍历不到元素。