Menu
Coddy logo textTech

Default Parameter Values

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

Optional parameters leave you a nil to handle. Often what you really want is a fallback value — "if the caller didn't say, assume X". Luau has no default syntax in the signature (there is no greeting: string = "Hello"); instead you use the classic Lua idiom, now with types:

function greet(name: string, greeting: string?): string
    greeting = greeting or "Hello"
    return `{greeting}, {name}`
end

print(greet("Alice"))            -- Hello, Alice
print(greet("Alice", "Howdy"))   -- Howdy, Alice

The parameter is annotated optional (string?), and the first line of the body replaces nil with the default. It works because nil is falsy — nil or "Hello" evaluates to "Hello". After that line, the checker knows greeting can no longer be nil.

One caveat you know from Lua: or also replaces false! For a boolean? parameter, flag = flag or true would silently override an explicit false. Use an explicit nil-check instead:

function ship(weight: number, expedited: boolean?): number
    if expedited == nil then
        expedited = false
    end
    -- ...
end
challenge icon

Challenge

Easy

Create a function named calculateTax taking price: number (required) and rate: number? defaulting to 0.05. Return the tax amount (price * rate) as a number.

Create a function named formatGreeting taking name: string (required) and timeOfDay: string? defaulting to "Hello". Return "[timeOfDay], [name]!" as a string.

Create a function named calculateShipping taking weight: number, distance: number (both required) and expedited: boolean? defaulting to false — use an explicit nil check for this one! Compute (weight * 0.5) + (distance * 0.1), and if expedited is true, multiply the result by 2. Return a number.

Call and print, each on its own line:

  1. calculateTax(100)
  2. calculateTax(200, 0.08)
  3. formatGreeting("Alice")
  4. formatGreeting("Bob", "Good morning")
  5. calculateShipping(5, 100)
  6. calculateShipping(3, 50, true)

Try it yourself

-- Write code here
-- calculateTax(price: number, rate: number?) -- default rate 0.05
-- formatGreeting(name: string, timeOfDay: string?) -- default "Hello"
-- calculateShipping(weight, distance, expedited: boolean?) -- default false
-- then print the six 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