Skip to content
AgileLogics
5 min read

Iterating with pairs and ipairs

Prerequisites: Arrays, Dictionaries and records

ipairs: arrays, in order

local fruits = {"apple", "banana", "cherry"}
for i, fruit in ipairs(fruits) do
  print(i, fruit)
end
1	apple
2	banana
3	cherry

ipairs visits 1, 2, 3, ... in order and stops at the first nil.

pairs: every key, in no particular order

local ages = {Ada = 36, Linus = 28, Grace = 45}

local names = {}
for name, age in pairs(ages) do
  names[#names + 1] = name .. "=" .. age
end
table.sort(names)
print(table.concat(names, ", "))
Ada=36, Grace=45, Linus=28

pairs visits every key — array part and string keys — but the order is not defined and can differ between runs. Collect and sort the keys when order matters, as above.

Ignoring a value with _

local scores = {90, 72, 85}
local total = 0
for _, score in ipairs(scores) do
  total = total + score
end
print(total)
247

_ is an ordinary variable name, used by convention for values you don't need.

Modifying while iterating

You may change or remove existing fields during pairs (t[k] = nil), but don't add new keys — the traversal becomes undefined. When removing from an array, loop backwards so indexes don't shift under you:

local numbers = {1, 2, 3, 4, 5, 6}
for i = #numbers, 1, -1 do
  if numbers[i] % 2 == 0 then
    table.remove(numbers, i)
  end
end
print(table.concat(numbers, " "))
1 3 5