next()

The next() function is used to retrieve the next key-value pair in a table iterator. It can be used to iterate through a table without relying on the pairs() or ipairs() functions directly. This function is particularly useful for custom iteration scenarios.

Syntax

next(table, key)

Parameters

  • Name
    table
    Type
    table
    Description

    The table from which to retrieve the next key-value pair.

  • Name
    key
    Type
    string|number|nil
    Description

    The current key from which to find the next key-value pair. If this is nil, the function returns the first key-value pair in the table.

Return

Returns the next key and its corresponding value from the table. If there are no more key-value pairs, nil is returned.

Description

The next() function provides a low-level mechanism for iterating through a table. If called with a valid key, it returns the next key-value pair in the table. If called with nil as the key, it returns the first key-value pair in the table. It is important to note that the order of key-value pairs is arbitrary.

Examples

Iterating through a table using next

local myTable = {
  name = "Bob",
  age = 25,
  job = "Artist"
}

local key, value = next(myTable)

while key do
  print(key, value)
  key, value = next(myTable, key)
end

-- Output:
-- name    Bob
-- age     25
-- job     Artist

Getting the first key-value pair

local colors = {
  red = "#FF0000",
  green = "#00FF00",
  blue = "#0000FF"
}

local key, value = next(colors)

print(key, value)  -- Output: one of the key-value pairs, e.g., red    #FF0000

See also

  • pairs(): A higher-level function that uses next() for iterating through all key-value pairs in a table.
  • ipairs(): Iterates over the numeric indices of a table in order.

Was this page helpful?

Table of Contents