Optional Parameters
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 26 of 80.
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
EasyWrite a profile function whose display name is optional.
- Write
local function createUserProfile(username: string, displayName: string?): string. - Return
`Profile: {displayName} (@{username})`whendisplayNameis given, otherwise`Profile: @{username}`. - Print
createUserProfile("john_doe", "John Doe")andcreateUserProfile("jane_smith").
Press Run Code: the output shows Profile: John Doe (@john_doe) and Profile: @jane_smith.
Try it yourself
-- 1) createUserProfile(username: string, displayName: string?): string
-- 2) print it with and without a display name
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