🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Pairs Metamethod

The __pairs metamethod controls how pairs walks a table. pairs calls it when it is present, and walks with next when it is not.

pairs visits every key without __pairs

A plain table has no __pairs. Counting the walk shows all three keys are visited.

local t = {a = 1, b = 2, c = 3}
local count = 0
for k, v in pairs(t) do
  count = count + 1
end
print(count)

Custom order reverses the walk

__pairs returns an iterator over a fixed order list. Building one string from the walk proves the reversed order.

local t = {a = 1, b = 2, c = 3}
local order = {"c", "b", "a"}
local mt = {}
mt.__pairs = function(tbl)
  local i = 0
  return function()
    i = i + 1
    local k = order[i]
    if k then return k, tbl[k] end
  end
end
setmetatable(t, mt)
local out = ""
for k, v in pairs(t) do
  if out ~= "" then out = out .. "," end
  out = out .. k .. "=" .. v
end
print(out)

Custom order can sort the keys

__pairs gathers the keys and sorts them first. The built string then runs in sorted order.

local t = {pear = 2, apple = 1, fig = 3}
local mt = {}
mt.__pairs = function(tbl)
  local keys = {}
  for k in next, tbl do
    keys[#keys + 1] = k
  end
  table.sort(keys)
  local i = 0
  return function()
    i = i + 1
    local k = keys[i]
    if k then return k, tbl[k] end
  end
end
setmetatable(t, mt)
local out = ""
for k in pairs(t) do
  if out ~= "" then out = out .. "," end
  out = out .. k
end
print(out)

Example

local stock = {banana = 5, apple = 2, cherry = 3}
local mt = {}
mt.__pairs = function(tbl)
  local keys = {}
  for k in next, tbl do
    keys[#keys + 1] = k
  end
  table.sort(keys)
  local i = 0
  return function()
    i = i + 1
    local k = keys[i]
    if k then return k, tbl[k] end
  end
end
setmetatable(stock, mt)
local out = ""
for k, v in pairs(stock) do
  if out ~= "" then out = out .. "," end
  out = out .. k .. "=" .. v
end
print(out)

Key points

  • __pairs: __pairs is a function in a metatable that defines custom iteration for pairs.
  • Fallback: without __pairs, pairs walks the table with next.
  • Iterator: the __pairs function supplies the iterator that pairs uses for the walk.
  • Custom order: a __pairs function can return keys in a chosen order, such as reversed or sorted.
  • Check: build one string from the visited keys to check a custom order.

In this example, __pairs gathers the stock keys and sorts them. The pairs walk then visits apple, banana, and cherry in that order. The built string proves the sorted order.

Note

a plain pairs walk over string keys has no fixed order, so sort or collect keys before printing them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A table has a __pairs metamethod that yields keys in sorted order. What does pairs do?