Declaring and Accessing Maps
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 16 of 73.
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
EasyCreate a typed map stock: {[string]: number} initialized with apples = 12 and bananas = 5. Then:
- add a new entry
cherrieswith the value20 - update
bananasto8
Finally print, each on its own line:
- the stock of
apples - the stock of
bananas - the stock of
cherries - the stock of
plums— a key you never set
Try it yourself
-- Write code here
-- 1) declare stock: {[string]: number} with apples = 12, bananas = 5
-- 2) add cherries = 20, update bananas to 8
-- 3) print apples, bananas, cherries, then plums
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