next()

Type Function
Library (globals)
Return value (varies)
Revision Release 2024.3703
Keywords pairs, ipairs, loops, iteration, table, array
See also pairs()
ipairs()

Overview

Allows a program to traverse all fields of an Array. next() returns the next index of the array and its associated value. When called with nil as its second argument, next() returns an initial index and its associated value. When called with the last index, or with nil in an empty array, next() returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether an array is empty.

The order in which the indices are enumerated is not specified, even for numeric indices. To traverse an array in numeric order, use a numerical for loop or the ipairs() function.

The behavior of next() is undefined if, during the traversal, you assign any value to a non-existent field in the array. You may, however, modify or clear existing fields.

Syntax

next( array [, index] )
array (required)

Array. The array that is being iterated.

index (optional)

Number. An index number of Array.

Examples

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