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)
endUse 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 falseFor strings and numbers or is safe, since only nil and false are falsy.
Challenge
EasyGive a boolean parameter a default of true that a false cannot undo.
- Write
local function shippingCost(weight: number, insured: boolean?): number. - Start it with
if insured == nil then insured = true end. - Return
weight * 0.5 + 2wheninsuredis true, otherwiseweight * 0.5. - Print
shippingCost(4)andshippingCost(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
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler