Menu
CoddyTech

Optional Parameters

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 26 of 80.

In plain Lua you could always omit arguments: the missing ones silently became nil, and forgetting to handle that was a classic source of bugs. Luau makes the possibility explicit: add ? to a parameter's type to mark it optional.

function greet(name: string, title: string?): string
    if title then
        return `{title} {name}`
    end
    return `Hello, {name}`
end

print(greet("Ada"))          -- Hello, Ada
print(greet("Ada", "Dr."))   -- Dr. Ada

string? reads as "string or nil". Callers may pass a string or skip the argument entirely; parameters without ? are required, and the checker flags calls that omit them.

Inside the function, an optional parameter might be nil, so check it before using it: if title then ... end is the standard pattern. Skip the check and concatenate nil into a string, and you get the same runtime error Lua always gave you; the type checker warns you first.

challenge icon

Challenge

Easy

Write a profile function whose display name is optional.

  1. Write local function createUserProfile(username: string, displayName: string?): string.
  2. Return `Profile: {displayName} (@{username})` when displayName is given, otherwise `Profile: @{username}`.
  3. Print createUserProfile("john_doe", "John Doe") and createUserProfile("jane_smith").

Press Run Code: the output shows Profile: John Doe (@john_doe) and Profile: @jane_smith.

Try it yourself

-- 1) createUserProfile(username: string, displayName: string?): string
-- 2) print it with and without a display name

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler