Optional Parameters
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 25 of 73.
In plain Lua you could always omit arguments — the missing ones silently became nil, and forgetting to handle that was a classic source of bugs. Luau makes the possibility explicit: add ? to a parameter's type to mark it optional.
function greet(name: string, title: string?): string
if title then
return `{title} {name}`
end
return `Hello, {name}`
end
print(greet("Ada")) -- Hello, Ada
print(greet("Ada", "Dr.")) -- Dr. Adastring? reads as "string or nil". Callers may pass a string or skip the argument entirely; parameters without ? are required, and the checker flags calls that omit them.
Inside the function, an optional parameter might be nil, so check it before using it — if title then ... end is the standard pattern. Skip the check and concatenate nil into a string, and you get the same runtime error Lua always gave you; the type checker warns you first.
Challenge
EasyCreate a function named createUserProfile that takes username: string (required) and displayName: string? (optional), returning a string:
- When both are provided, return:
"Profile: [displayName] (@[username])" - When only the username is provided, return:
"Profile: @[username]"
Create a function named calculateDiscount that takes price: number (required) and membershipLevel: string? (optional), returning a number:
- When a membership level is provided, return the price reduced by 10% (multiply by
0.9) - Otherwise return the price unchanged
Call and print, each on its own line:
createUserProfile("john_doe", "John Doe")createUserProfile("jane_smith")calculateDiscount(100, "premium")calculateDiscount(75)
Try it yourself
-- Write code here
-- createUserProfile(username: string, displayName: string?): string
-- calculateDiscount(price: number, membershipLevel: string?): number
-- then print the four results
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps