pairs()

The pairs() function is used to iterate over all key-value pairs in a table, allowing you to access each key and its corresponding value. It returns an iterator function that can be used in a for loop or with the ipairs() function for more structured iteration.

Syntax

pairs(table)

Parameters

  • Name
    table
    Type
    table
    Description

    The table whose key-value pairs will be iterated over.

Return

Returns an iterator function, which can be used to traverse the table. The iterator yields each key-value pair as a series of calls.

Description

The pairs() function is particularly useful for iterating over non-numeric keys in a table or for tables with a mix of numeric and non-numeric keys. Unlike the ipairs() function, which iterates over only the numeric keys in a table in sequential order, pairs() iterates over all keys in an arbitrary order.

Examples

Iterating over a table with pairs

local myTable = {
  name = "Alice",
  age = 30,
  occupation = "Engineer"
}

for key, value in pairs(myTable) do
  print(key, value)
end

-- Output:
-- name    Alice
-- age     30
-- occupation    Engineer

Using pairs with a mixed table

local mixedTable = {
  [1] = "First",
  [2] = "Second",
  color = "Blue",
  number = 42
}

for key, value in pairs(mixedTable) do
  print(key, value)
end

-- Output:
-- 1      First
-- 2      Second
-- color  Blue
-- number 42

See also

  • ipairs(): Iterates over the numeric indices of a table in order.
  • next(): Retrieves the next key-value pair from a table iterator.

Was this page helpful?

Table of Contents