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}`)
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
EasyPrint a week of temperatures and their total.
- Declare
local temps: {number} = {12, 15, 11, 14}andlocal total = 0. - Loop with
for day: number, temp: number in ipairs(temps) do, print`Day {day}: {temp}`and addtemptototal. - 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
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler