Menu
CoddyTech

Default Parameter Values

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

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.

challenge icon

Challenge

Easy

Give an optional parameter a default value.

  1. Write local function calculateTax(price: number, rate: number?): number.
  2. Its first line is rate = rate or 0.05; then return price * rate.
  3. Print calculateTax(100) and calculateTax(200, 0.08).

Press Run Code: the output shows 5, then 16.

Try it yourself

-- 1) calculateTax(price: number, rate: number?): number
--    default rate 0.05 with the `or` idiom
-- 2) print calculateTax(100) and calculateTax(200, 0.08)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler