Menu
Coddy logo textTech

Optional Parameters

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 25 of 73.

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

Create a function named createUserProfile that takes username: string (required) and displayName: string? (optional), returning a string:

  • When both are provided, return: "Profile: [displayName] (@[username])"
  • When only the username is provided, return: "Profile: @[username]"

Create a function named calculateDiscount that takes price: number (required) and membershipLevel: string? (optional), returning a number:

  • When a membership level is provided, return the price reduced by 10% (multiply by 0.9)
  • Otherwise return the price unchanged

Call and print, each on its own line:

  1. createUserProfile("john_doe", "John Doe")
  2. createUserProfile("jane_smith")
  3. calculateDiscount(100, "premium")
  4. calculateDiscount(75)

Try it yourself

-- Write code here
-- createUserProfile(username: string, displayName: string?): string
-- calculateDiscount(price: number, membershipLevel: string?): number
-- then print the four results
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