Union Types
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 31 of 73.
Sometimes one type isn't enough. A user id might arrive as "user123" or as 42. In plain Lua you'd just hope for the best; Luau gives you union types — the pipe | reads as "or":
local userId: number | string
userId = "user123" -- ✓ a string is allowed
userId = 42 -- ✓ a number is allowed
userId = true -- ✗ type error: boolean isn't in the unionThe variable can hold either member of the union — and only those. That's the crucial difference from any: a union stays strict about what's allowed while giving you the flexibility you need.
Unions are especially useful for function parameters that accept multiple input formats:
function printId(id: number | string): ()
print(id)
end
printId(42) -- works with a number
printId("user123") -- works with a stringYou already know string? — that was your first union! It's simply shorthand for string | nil. In the next lesson you'll learn how to safely work with a union value once you have one.
Challenge
EasyCreate a function named printId that takes id: number | string and prints it — explicit return type ().
Declare a variable status of type string | number, initialized to "active".
Then, in order:
- Call
printId(42) - Call
printId("user123") - Print
status - Reassign
statusto200and print it again
Four lines of output in total.
Try it yourself
-- Write code here
-- printId(id: number | string): ()
-- local status: string | number = "active"
-- call printId(42), printId("user123"),
-- print status, reassign to 200, print again
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