Menu
CoddyTech

Index Signatures

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 78 of 80.

You met map types like {[string]: number} back in the tables chapter: an index signature: any string key maps to a number value. They shine when the keys aren't known while you write the code: counters, settings, caches, scores: anything built up at runtime.

type Counts = {[string]: number}

local counts: Counts = {}
counts["potion"] = 3   -- any string key is allowed
counts["sword"] = 1
counts["potion"] += 1  -- values are checked as numbers

Two runtime facts matter when working with maps. First, reading a key that was never set returns nil: the classic counting pattern handles that with or, turning "missing" into 0:

counts[item] = (counts[item] or 0) + 1

Second, pairs() iterates a map's keys in no guaranteed order: running the same program twice can visit keys differently. Whenever output must be predictable, collect the keys into an array, table.sort them, and iterate the sorted array instead:

local keys: {string} = {}
for key in pairs(counts) do
    table.insert(keys, key)
end
table.sort(keys)
for _, key in ipairs(keys) do
    print(`{key}: {counts[key]}`)
end
challenge icon

Challenge

Easy

Keep scores for players whose names you do not know in advance.

  1. Write type Scores = {[string]: number} and create local scores: Scores = {}.
  2. Add points: scores["mia"] = (scores["mia"] or 0) + 5, then the same for "leo" with 3.
  3. Print scores["mia"], scores["leo"] and scores["zed"].

Press Run Code: the output shows 5, 3 and nil.

Try it yourself

-- 1) type Scores = {[string]: number}, then local scores: Scores = {}
-- 2) add 5 points for "mia" and 3 for "leo"
-- 3) print mia, leo and zed

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler