Menu
CoddyTech

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

Keep a typed map of school supplies.

  1. Declare local stock: {[string]: number} = {pens = 40, rulers = 15}.
  2. Add stock["erasers"] = 25 and change rulers to 10.
  3. Print the stock of pens, rulers, erasers and glue, 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

Practice on your own: Online Luau compiler