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}`)
endRemember 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}`)
endOne 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
EasyCreate 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps