Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 32 ยท Control Flow

Iterating with pairs and ipairs

Walk over Lua tables with ipairs and pairs, learn what order to expect, how to modify a table safely during a loop, and how the generic for works.

Almost every Lua program stores its data in tables, so walking over a table is one of the most common jobs you will do. Lua does it with the generic for loop, which takes an iterator and calls it again and again until it runs out of items. You rarely write iterators yourself. Instead you use two ready-made ones: ipairs for list-like tables and pairs for everything else.

This lesson explains how they differ, what you can and cannot count on about order, what is safe to change while looping, and how the generic for works underneath. Tables themselves are introduced properly in Tables as Arrays and Dictionaries; here a quick picture is enough: a table is a collection of key-value pairs, and a list is a table whose keys are 1, 2, 3, and so on. Lua is not installed on this site, so the Lua code is read-only and the runnable examples are JavaScript stand-ins.

ipairs: lists in order

ipairs(t) visits the keys 1, 2, 3, ... in that order and gives you each index and value. It stops at the first nil:

LUA
local fruits = {"apple", "banana", "cherry"}

for index, name in ipairs(fruits) do
  print(index, name)
end
-- 1   apple
-- 2   banana
-- 3   cherry

The order is guaranteed, which is why ipairs is the right tool for lists. The "stops at the first nil" part matters when a list has a hole:

LUA
local data = {10, 20, nil, 40}

for i, v in ipairs(data) do
  print(i, v)
end
-- 1   10
-- 2   20
-- (stops here: data[3] is nil)

The element 40 is never visited, even though it exists at key 4. Holes in lists cause many bugs, so avoid them if you can. If you only need the values, write for _, v in ipairs(t). The name _ is just a normal variable that people use to say "I don't care about this one".

pairs: every entry

pairs(t) visits every key-value pair, whatever the keys are: numbers, strings, even tables:

LUA
local person = {name = "Ada", age = 36, 10, 20}

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

This table has two list items (keys 1 and 2) and two named fields. All four are visited. But in which order?

Order: what you can and cannot count on

The Lua manual says that the order in which pairs enumerates the table is not specified, even for numeric keys. In practice the items stored in the array part usually come out first in order, followed by the hash part in an order that looks random and can change between runs, between Lua versions, or after the table has been modified. Do not write code that depends on it.

If you need a stable order, collect the keys, sort them, and loop over the sorted list:

LUA
local scores = {carol = 88, alice = 95, bob = 71}

local names = {}
for name in pairs(scores) do
  names[#names + 1] = name
end
table.sort(names)

for _, name in ipairs(names) do
  print(name, scores[name])
end
-- alice   95
-- bob     71
-- carol   88

Notice for name in pairs(scores): when you ask for only one variable you get just the key. This is the standard way to build a sorted report. Sorting is covered in The table Library.

ipairs or pairs?

ipairs Keys 1, 2, 3 in order. Stops at the first nil.
pairs Every key, any type. Order not specified.

Lists use ipairs. Dictionaries use pairs.

1 / 2

Try it: ipairs, pairs and a sorted report

The stand-in below models both iterators in JavaScript. ipairs stops at the first missing value, like Lua's, and the dictionary report sorts the keys first so the output is always the same.

JS ipairs and pairs stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Modifying a table while looping

There is one firm rule in the manual: the behavior of pairs is undefined if you assign to a field that does not exist during the traversal. In other words, do not add new keys while looping over a table. You may, however, change the value of an existing field or clear an existing field by assigning nil:

LUA
local stock = {apples = 0, pears = 4, plums = 0, figs = 2}

for item, count in pairs(stock) do
  if count == 0 then
    stock[item] = nil      -- allowed: clearing a field during traversal
  end
end
-- stock now holds pears and figs only

Removing items from a list while you walk it with ipairs or an ascending for is a different trap. If you remove item 2, the old item 3 slides into position 2, and the loop moves on to 3, so one element is skipped. Walk backward instead:

LUA
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
-- numbers is now {1, 3, 5}

Going from the end means the items you have not visited yet never move. If you need to add or remove many keys, build a second table instead of editing the one you are traversing.

next and what generic for really is

pairs is a thin wrapper around a function named next. next(t) returns the first key-value pair of t, and next(t, key) returns the pair that follows key. When there is nothing left it returns nil. That also gives the standard test for an empty table:

LUA
local t = {}
print(next(t) == nil)    --> true
t.x = 1
print(next(t) == nil)    --> false

Now the generic for. This loop:

LUA
for k, v in pairs(t) do
  body(k, v)
end

works roughly as if you had written this:

LUA
do
  local iterator, state, control = pairs(t)   -- pairs returns next, t, nil
  while true do
    local k, v = iterator(state, control)
    if k == nil then break end
    control = k
    body(k, v)
  end
end

After in there is an expression list that supplies up to three values: an iterator function, a state that is passed to it every time, and an initial control value. Each pass calls iterator(state, control). The first result becomes the new control value and the first loop variable; when it is nil the loop ends. (Lua 5.4 also accepts an optional fourth value, a to-be-closed variable, which is a topic for Error Handling.) ipairs(t) simply returns a small iterator, the table, and the starting control value 0.

That explains why you can loop over anything that returns this triple, including string.gmatch for text and functions you write yourself, which you will see in later lessons on closures and patterns.

Try it: a hand-made iterator

Here is a stand-in for writing your own stateless-style iterator. The range function returns an iterator and the loop calls it until it returns undefined (Lua's nil).

JS How the generic for calls an iterator (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ipairs do when it meets a nil value in the middle of a list?

    ipairs counts up through 1, 2, 3, ... and ends at the first index whose value is nil, so anything after a hole is not visited.
  2. 2. Which statement about the order of pairs is correct?

    The manual does not specify the order. Collect the keys into a list, sort it, and loop over that.
  3. 3. Which change is allowed during a pairs traversal?

    Clearing existing fields (or changing their values) is permitted. Assigning to a field that does not yet exist makes the behavior undefined.
  4. 4. What three things can follow in in a generic for?

    The generic for calls the iterator with the state and the previous control value on each pass, and stops when the first result is nil.

Summary

  • ipairs(t) walks keys 1, 2, 3, ... in order and stops at the first nil; use it for lists.
  • pairs(t) visits every entry, but the order is not specified. Sort the keys when order matters.
  • During a traversal you may change values or set existing fields to nil; do not add new keys.
  • To delete items from a list while looping, count backward.
  • next(t) == nil tests whether a table is empty.
  • The generic for calls an iterator function with a state and a control value until it returns nil.

Next, build your own reusable pieces in Functions.