Menu
Coddy logo textTech

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

Process user profile fields that might be missing. Start your file with --!strict.

  • getDisplayName(fullName: string?): string — returns fullName if it isn't nil, otherwise Anonymous User.
  • formatEmail(email: string?): string — returns the email lowercased (string.lower) if it isn't nil, otherwise No email provided.
  • getUserInfo(name: string?, email: string?): string — uses both functions and returns Name: [processed name], Email: [processed email].

Then print, each on its own line:

  1. getDisplayName("John Smith")
  2. getDisplayName(nil)
  3. formatEmail("ALICE@EXAMPLE.COM")
  4. formatEmail(nil)
  5. getUserInfo("Bob Johnson", "bob@test.com")
  6. getUserInfo(nil, nil)
  7. 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
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