Tables, lesson 18
Looping over tables
Goal: Do something with every item.
about 5 min3 practice exercises
To do something with every item in a table, loop over it with for ... in.
For an array you get each position and value, in order:
local inventory = { "Sword", "Shield", "Potion" }
for index, item in inventory do
print(index, item)
end
This prints 1 Sword, 2 Shield, 3 Potion. If you do not need the position, name it _ by convention: for _, item in inventory do.
For a dictionary you get each key and value:
local coinValues = { Bronze = 1, Silver = 5, Gold = 25 }
local total = 0
for coinType, value in coinValues do
total += value
end
print(total) -- 31
You will often see pairs(t) and ipairs(t) in older scripts. They still work. Looping over the table directly, as above, is the current Luau style.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.