Union Types
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 33 of 80.
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
EasyAccept a value that is a number or a string.
- Write
local function printId(id: number | string): ()that printsid. - Declare
local status: string | number = "active". - Call
printId(7)andprintId("player7"), then setstatus = 200and print it.
Press Run Code: the output shows 7, player7 and 200.
Try it yourself
-- 1) printId(id: number | string): ()
-- 2) local status: string | number = "active"
-- 3) call printId(7) and printId("player7"), set status to 200, print it
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