next()

类型 函数
(全局)
返回值 (不定)
修订 版本 2024.3703
关键词 键值对, 索引对, 循环, 迭代, 表, 数组
另请参阅 pairs()
ipairs()

概览

允许程序遍历数组的所有字段。next() 返回数组的下一个索引及其关联的值。当第二个参数为 nil 时,next() 返回初始索引及其关联的值。当使用最后一个索引调用,或者在空数组中使用 nil 调用时,next() 返回 nil。如果第二个参数不存在,则将其解释为 nil。特别是,您可以使用 next(t) 来检查数组是否为空。

枚举索引的顺序未指定,即使对于数字索引也是如此。要按数字顺序遍历数组,请使用数字 for 循环或 ipairs() 函数。

如果在遍历期间,您为数组中不存在的字段赋值,则 next() 的行为未定义。但是,您可以修改或清除现有字段。

语法

next( array [, index] )
数组 (必填)

数组 正在迭代的数组。

索引 (可选)

数字 数组的索引号。

示例

local tableWithoutIndexes = { 10, 20, 30, 40, 50 }

for key, value in next, tableWithoutIndexes, nil do
    print( "The key " .. key .. " has the value: " .. value )
end
-- Note that for tables containing indexes, next() will return the values in an arbitrary order

local tableWithIndexes = { first = 10, second = 20, third = 30, fourth = 40, fifth = 50 }

for key, value in next, tableWithIndexes, nil do
    print( "The key " .. key .. " has the value: " .. value )
end