Menu
Coddy logo textTech

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 set

The 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 icon

Challenge

Easy

Create a typed map stock: {[string]: number} initialized with apples = 12 and bananas = 5. Then:

  1. add a new entry cherries with the value 20
  2. update bananas to 8

Finally print, each on its own line:

  1. the stock of apples
  2. the stock of bananas
  3. the stock of cherries
  4. 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
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