Declaring and Accessing Maps
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 16 of 80.
Declaring a typed map looks like the table constructors you've always written: the annotation just pins down the key and value types:
local stock: {[string]: number} = {apples = 12, bananas = 5}Reading and writing use the indexing you know. For keys that are valid identifiers, stock.apples and stock["apples"] reach the same entry; bracket form also handles keys with spaces or ones stored in variables:
stock["cherries"] = 20 -- add a new entry
stock.bananas = 8 -- update an existing one
print(stock["apples"]) -- 12
print(stock["plums"]) -- nil: never setThe type checker watches every write: stock["apples"] = "many" is flagged because "many" isn't a number, and using a number as a key is flagged because keys must be strings.
To delete an entry, assign nil to its key: stock["bananas"] = nil removes it entirely, and later reads give nil. There's no separate delete function; this is the standard Lua idiom, and it still type-checks on a map.
Challenge
EasyKeep a typed map of school supplies.
- Declare
local stock: {[string]: number} = {pens = 40, rulers = 15}. - Add
stock["erasers"] = 25and changerulersto10. - Print the stock of
pens,rulers,erasersandglue, one per line.
Press Run Code: the output shows 40, 10, 25 and nil.
Try it yourself
-- 1) declare stock: {[string]: number} with pens = 40, rulers = 15
-- 2) add erasers = 25, change rulers to 10
-- 3) print pens, rulers, erasers, then glue
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