Iterating Tables with pairs and ipairs
Traverse tables safely using pairs() and ipairs().
ipairs: Ordered Array Iteration
ipairs(t) iterates over the integer sequence starting at index 1, yielding (index, value) pairs. It stops at the first nil. This is the safe, predictable choice for array-like tables where order matters.
local fruits = {"apple","banana","cherry"}
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
-- 1 apple
-- 2 banana
-- 3 cherrypairs: All Keys
pairs(t) iterates over every non-nil key-value pair in the table, in unspecified order. It uses the next() function internally. Use pairs for dictionaries, mixed tables, or when you need to visit all keys regardless of type.
local info = {name="Lua", version=5.4, embedded=true}
for k, v in pairs(info) do
print(k, v)
end
-- name Lua
-- version 5.4
-- embedded true (order may vary)All lessons in this course
- Tables as Arrays
- Tables as Dictionaries
- Iterating Tables with pairs and ipairs
- Nested Tables and Structured Data