Lua Table Iteration
Table iteration means visiting every slot in a table one by one. Lua offers ipairs for the array part in order and pairs for every key.
ipairs walks in order
ipairs gives the index and the value on each step. string.format builds each numbered line.
local fruit = {"apple", "banana", "cherry"}
for i, v in ipairs(fruit) do
print(string.format("%d: %s", i, v))
endpairs counts every entry
pairs visits every key, but the order is not promised. Counting the visits is safe because a count does not depend on order.
local caps = {france = "Paris", spain = "Madrid", italy = "Rome"}
local count = 0
for k, v in pairs(caps) do
count = count + 1
end
print(count)Two loops, same lines
A numeric for loop and ipairs both walk the array part in order. Each loop prints the same three lines.
local fruit = {"apple", "banana", "cherry"}
for i = 1, #fruit do
print(i .. ": " .. fruit[i])
end
for i, v in ipairs(fruit) do
print(i .. ": " .. v)
endExample
local scores = {95, 88, 76}
local total = 0
for i, v in ipairs(scores) do
print(string.format("Rank %d: %d", i, v))
total = total + v
end
print("Total: " .. total)Key points
- Iteration: Iteration visits each slot in a table one step at a time.
- ipairs: The loop for i, v in ipairs(t) do visits the numbered slots in order.
- pairs: The loop for k, v in pairs(t) do visits every key in the table.
- Order: pairs makes no promise about the order it visits keys in.
- Numeric for: A numeric for loop from 1 to #t also walks the array part in order.
In this example, ipairs walks the scores in order and string.format prints each one with its rank. Each score is added to total inside the loop. The final print shows the total 259 after the loop ends.
Note
Use ipairs when order matters and pairs when only the full set of keys matters.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which loop is the right choice to print an array in exact slot order?