Menu
CoddyTech

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 mode

The 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"
end

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

Challenge

Easy

Give a name that might be missing a safe fallback.

  1. Keep --!strict on the first line.
  2. Write local function getDisplayName(fullName: string?): string returning fullName when it is not nil, otherwise "Anonymous User".
  3. Print getDisplayName("John Smith") and getDisplayName(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

Practice on your own: Online Luau compiler