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, AliceThe 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
EasyGive an optional parameter a default value.
- Write
local function calculateTax(price: number, rate: number?): number. - Its first line is
rate = rate or 0.05; then returnprice * rate. - Print
calculateTax(100)andcalculateTax(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
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