Menu
CoddyTech

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 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 two typed variables now and give them values later.

  1. Write local totalScore: number, then totalScore = 95 on the next line.
  2. Write local playerName: string, then playerName = "Alex" on the next line.
  3. Print totalScore, then playerName.

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

Practice on your own: Online Luau compiler