Iterating with pairs and ipairs
ipairs walks arrays in order, and pairs visits every key in a table.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting pairs to return keys in insertion order
- Using ipairs on a table with holes and stopping early
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: