Menu
Coddy logo textTech

Explicit Type Annotations

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 11 of 73.

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 number

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

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

Challenge

Easy

Declare a variable named totalScore with the explicit type number, without assigning an initial value. On the next line, assign it the value 95.

Then declare a variable named playerName with the explicit type string, again without an initial value. On the next line, assign it the value "<code>Alex".

Finally, print both variables on separate lines — first totalScore, then playerName.

Try it yourself

-- Write code here
-- 1) declare totalScore: number (no value), then assign 95
-- 2) declare playerName: string (no value), then assign the exact text from the instructions
-- 3) print totalScore, then playerName
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

Practice on your own: Online Lua compiler