Using Literal Union Enums
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 58 of 80.
Literal unions earn their keep as function parameters. Type a parameter with the union and the checker guarantees the function is only ever called with a valid member:
type Direction = "up" | "down" | "left" | "right"
local function move(direction: Direction)
print(`Moving {direction}...`)
end
move("left") -- ✓
move("north") -- ✗ type error: not a DirectionInside the function, handle the members exhaustively with an if/elseif chain. Since the type limits the input to four values, checking three and letting else take the last one covers everything:
local function describe(direction: Direction): string
if direction == "up" then
return "Going upward"
elseif direction == "down" then
return "Going downward"
elseif direction == "left" then
return "Turning left"
else
return "Turning right"
end
endOne wrinkle: strings arriving from outside, like io.read(), are typed as plain string, because the checker can't know what a user will type. Luau's cast operator :: fixes that: value :: Type tells the checker to treat the value as that type. The Type Assertions lesson near the end of this section covers casts in full; for now, one line is enough:
local direction = io.read() :: DirectionA cast is a promise, not a check, at runtime nothing verifies the input. Production code would validate first; here it lets typed functions accept user input cleanly.
Challenge
EasyTurn a direction typed by the player into an action.
- Write
type Direction = "up" | "down" | "left" | "right". - Write
local function getAction(direction: Direction): stringreturning"Climb","Drop","Turn left"or"Turn right". - Read
local direction = io.read() :: Directionand printgetAction(direction).
Press Run Code: with the input up, the output shows Climb.
Try it yourself
-- 1) type Direction
-- 2) getAction(direction: Direction): string
-- 3) local direction = io.read() :: Direction, then print the action
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 Combos8Enums, the Luau Way
The Enum Pattern in LuauNumeric Enums with TablesString Enums as UnionsUsing Literal Union EnumsFreezing Constant TablesRecap: Enums, the Luau Way3Typed 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