Explicit Type Annotations
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 11 of 80.
Knowing when to write annotations and when to lean on inference is a core Luau skill. The most common case that needs an explicit annotation: declaring a variable without an initial value.
local score: number -- no value yet: annotate the intent
score = 85 -- assigned later, checked against numberWith no initializer there's no value to infer from. In the default nonstrict mode an unannotated, uninitialized variable is treated as any: losing the safety you came to Luau for. The explicit : number locks the intended type from the start, so only numbers can ever be assigned:
local score: number
score = "85" -- ✗ type error: string is not a numberAt runtime, remember, a declared-but-unassigned variable simply holds nil until the assignment happens: the annotation documents and enforces what it will hold.
Annotations also shine wherever the type isn't obvious from the code: function parameters, return types, and empty tables you'll fill later. Rule of thumb: infer when the value is right there, annotate when it isn't.
Challenge
EasyDeclare two typed variables now and give them values later.
- Write
local totalScore: number, thentotalScore = 95on the next line. - Write
local playerName: string, thenplayerName = "Alex"on the next line. - Print
totalScore, thenplayerName.
Press Run Code: the output shows 95 and Alex.
Try it yourself
-- 1) declare totalScore as a number with no value, then assign 95
-- 2) declare playerName as a string with no value, then assign "Alex"
-- 3) print totalScore, then playerName
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 Combos3Typed 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