Nil Safety In Strict Mode
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 77 of 80.
The most common Lua crash is "attempt to index nil": code that assumed a value existed when it didn't. Luau's answer is nil discipline: under --!strict, a plain string can never be nil. If nil is a real possibility, the type must say so with ?:
--!strict
local nickname: string? = nil -- ok: string OR nil
local username: string = nil -- ✗ type error in strict modeThe discipline cuts both ways: given a string?, strict mode won't let you use it as a string until you've ruled out nil. The standard tool is a plain comparison, which narrows just like a typeof guard:
local function shout(name: string?): string
if name ~= nil then
return string.upper(name) -- name is string here
end
return "NOBODY"
endWhen nil would be a bug rather than a valid case, use assert: after assert(x ~= nil) the checker treats x as non-nil for the rest of the scope, and at runtime the assert crashes early, at the point of the broken assumption, instead of somewhere far away.
The payoff: the checker forces every "might be missing" value to be handled while you edit, and the runtime error simply never happens.
Challenge
EasyGive a name that might be missing a safe fallback.
- Keep
--!stricton the first line. - Write
local function getDisplayName(fullName: string?): stringreturningfullNamewhen it is notnil, otherwise"Anonymous User". - Print
getDisplayName("John Smith")andgetDisplayName(nil).
Press Run Code: the output shows John Smith and Anonymous User.
Try it yourself
--!strict
-- 1) getDisplayName(fullName: string?): string, falling back to "Anonymous User"
-- 2) print it for "John Smith" and nil
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