«

Lua pairs ipairs区别

时间:2016-9-19     作者:new     分类: Lua笔记


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,并且除了迭代器本身以及遍历表本身还可以返回nil;

ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。

ipairs适用于数组,pairs适用于键值表。