Nil Safety In Strict Mode
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 71 of 73.
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
EasyProcess user profile fields that might be missing. Start your file with --!strict.
getDisplayName(fullName: string?): string— returnsfullNameif it isn'tnil, otherwiseAnonymous User.formatEmail(email: string?): string— returns the email lowercased (string.lower) if it isn'tnil, otherwiseNo email provided.getUserInfo(name: string?, email: string?): string— uses both functions and returnsName: [processed name], Email: [processed email].
Then print, each on its own line:
getDisplayName("John Smith")getDisplayName(nil)formatEmail("ALICE@EXAMPLE.COM")formatEmail(nil)getUserInfo("Bob Johnson", "bob@test.com")getUserInfo(nil, nil)getUserInfo("Sarah Wilson", nil)
Try it yourself
--!strict
-- Write code here
-- 1) getDisplayName(fullName: string?): string — nil-check, fallback "Anonymous User"
-- 2) formatEmail(email: string?): string — string.lower or "No email provided"
-- 3) getUserInfo(name: string?, email: string?): string — combine both
-- 4) print the seven test calls from the task
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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: Fine-Tuning Types3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps