Menu
CoddyTech

Iterating Tables

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 17 of 80.

You've looped over Lua tables plenty of times: Luau keeps the exact same loops and adds types to the loop variables. For arrays, ipairs walks the elements in order, index 1 to #t, and you can annotate both variables:

local temps: {number} = {18, 21, 19}
for day: number, temp: number in ipairs(temps) do
    print(`Day {day}: {temp}`)
end

Remember ipairs stops at the first missing index: a nil hole in the middle ends the loop early. That's rarely an issue with well-kept arrays, but worth knowing.

For maps, use pairs, which visits every key/value pair: string keys included. On a {[string]: number} map, the loop variables are naturally a string and a number:

local ages: {[string]: number} = {Alice = 30, Bob = 25}
for name: string, age: number in pairs(ages) do
    print(`{name} is {age}`)
end

One crucial caveat: pairs visits hash-part keys in no guaranteed order. It can differ between runs. When you need deterministic output (sorted reports, tests), collect the keys into an array, table.sort it, then loop over the sorted keys with ipairs and index the map.

challenge icon

Challenge

Easy

Print a week of temperatures and their total.

  1. Declare local temps: {number} = {12, 15, 11, 14} and local total = 0.
  2. Loop with for day: number, temp: number in ipairs(temps) do, print `Day {day}: {temp}` and add temp to total.
  3. After the loop, print total.

Press Run Code: the output shows Day 1: 12 to Day 4: 14, then 52.

Try it yourself

-- 1) declare temps: {number} and total = 0
-- 2) loop with typed day and temp, print each day, add to total
-- 3) print the total

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler