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 numbersTwo 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) + 1Second, 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]}`)
endChallenge
EasyKeep scores for players whose names you do not know in advance.
- Write
type Scores = {[string]: number}and createlocal scores: Scores = {}. - Add points:
scores["mia"] = (scores["mia"] or 0) + 5, then the same for"leo"with3. - Print
scores["mia"],scores["leo"]andscores["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
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 Combos8Enums, the Luau Way
The Enum Pattern in LuauNumeric Enums with TablesString Enums as UnionsUsing Literal Union EnumsFreezing Constant TablesRecap: Enums, the Luau Way11Advanced Topics
Type AssertionsType Guards With typeofThe never TypeNil Safety In Strict ModeIndex SignaturesRecap: Config Value TypesRecap: Fine-Tuning Types3Typed 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