Menu
CoddyTech

Defaults for Booleans

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

One caveat you know from Lua: or also replaces false. For a boolean? parameter that should default to true, flag = flag or true turns an explicit false into true, because false or true is true:

local function sendAlert(message: string, loud: boolean?)
    loud = loud or true   -- sendAlert("Hi", false) still gets true
    print(message, loud)
end

Use an explicit nil check instead. It fills in the default only when the argument was left out:

local function sendAlert(message: string, loud: boolean?)
    if loud == nil then
        loud = true
    end
    print(message, loud)
end

sendAlert("Hi")         -- Hi  true
sendAlert("Hi", false)  -- Hi  false

For strings and numbers or is safe, since only nil and false are falsy.

challenge icon

Challenge

Easy

Give a boolean parameter a default of true that a false cannot undo.

  1. Write local function shippingCost(weight: number, insured: boolean?): number.
  2. Start it with if insured == nil then insured = true end.
  3. Return weight * 0.5 + 2 when insured is true, otherwise weight * 0.5.
  4. Print shippingCost(4) and shippingCost(4, false).

Press Run Code: the output ends with 4 and 2.

Try it yourself

-- Default via the `or` idiom
local function calculateTax(price: number, rate: number?): number
    rate = rate or 0.05
    return price * rate
end

print(calculateTax(100))
print(calculateTax(200, 0.08))

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler