← Back to course
medium ✦ 75 Studs

Looping Over Tables

Walk every item in a table with ipairs and pairs, then add them up.

You know how to build tables: arrays like {10, 25, 40} and dictionaries like {name = "smartyhead01"}. The next superpower is visiting every item without typing each one out by hand. That is iteration, and Lua gives you two tools for it: ipairs and pairs.

Use ipairs for arrays, the lists with number slots 1, 2, 3. It hands you the slot number and the value, in order:

local scores = {10, 25, 40}
for index, value in ipairs(scores) do
  print("Slot " .. index .. " holds " .. value)
end

That walks the list top to bottom: slot 1 holds 10, slot 2 holds 25, slot 3 holds 40. The loop figures out how many items there are, so you never have to count them yourself. Add a fourth score to the table and the same loop just handles it. That is the whole point: write the loop once, and it scales to any size list.

Use pairs for dictionaries, the tables with named keys, where order does not matter:

local stats = {speed = 16, jump = 50, health = 100}
for key, value in pairs(stats) do
  print(key .. " = " .. value)
end

Same idea, but now key is a name like speed instead of a slot number. Quick rule of thumb: number slots, reach for ipairs; named keys, reach for pairs.

A super common move is summing a list. You start a total at zero, then add each value as you walk the table:

local total = 0
for index, value in ipairs(scores) do
  total = total + value
end
print("Total: " .. total)

That running-total pattern shows up everywhere: adding up a player’s cash, counting points across rounds, tallying inventory. Learn it once, reuse it forever.

Now make it yours: print the exact Total score: 75 line by summing the scores list, then try the same loop on a list of your own, maybe ball weights or level scores, and print both each item and the grand total at the end.

Output
Click Run to see your output.