Menu
Coddy logo textTech

Iterating Tables

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 17 of 73.

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

Create a typed array temps: {number} initialized with 18, 21, 19 and 24.

Loop over it with ipairs, annotating both loop variables (day: number, temp: number). For each element print exactly:

Day 1: 18

(using string interpolation with backticks), and add each temperature to a running total.

After the loop, print the total on its own line.

Try it yourself

-- Write code here
-- 1) declare temps: {number} = {18, 21, 19, 24}
-- 2) for day: number, temp: number in ipairs(temps) do ... end
--    printing `Day {day}: {temp}` and summing into total
-- 3) print the total after the loop
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau