← Back to Lua Course | Chapter 4: Tables | Lesson 4 of 7

Iterating with pairs and ipairs

ipairs walks arrays in order, and pairs visits every key in a table.

Iterating with pairs and ipairs

ipairs(t) iterates over keys 1, 2, 3 and so on and stops at the first nil. pairs(t) visits every key and value, in no guaranteed order. Use ipairs for sequences and pairs for dictionaries, and do not add new keys to a table while you iterate over it.

Note: Sort the keys first if you need a stable printing order from pairs.

Example: Iterating with pairs and ipairs

lua
local list = {"a", "b", nil, "d"}
for i, v in ipairs(list) do print(i, v) end

local ages = {ann = 30, bob = 25, cid = 41}
local keys = {}
for k in pairs(ages) do keys[#keys + 1] = k end
table.sort(keys)
for _, k in ipairs(keys) do print(k, ages[k]) end

-- Output:
-- 1	a
-- 2	b
-- ann	30
-- bob	25
-- cid	41
Common Mistakes
  1. Expecting pairs to return keys in insertion order
  2. Using ipairs on a table with holes and stopping early
  3. Adding new keys inside a pairs loop
Chapter Summary
  • ipairs goes 1..n until nil
  • pairs visits all keys
  • pairs order is not defined
  • Do not add keys while iterating

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.