String Enums as Unions
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 53 of 73.
Numbers make cryptic logs: seeing 2 tells you little, seeing "down" tells you everything. For readable enums, Luau's literal union types are the tool — a type whose members are exact strings:
type Direction = "up" | "down" | "left" | "right"
local facing: Direction = "up" -- ✓
local typo: Direction = "upp" -- ✗ type error while editingA variable annotated with Direction can hold those four strings and nothing else. Misspell one and the checker catches it instantly — the bug never reaches a player.
At runtime the values are plain strings. Print them, concatenate them, compare them with == — everything you know about strings applies:
print(facing) -- up
print(`facing {facing}`) -- facing upCompare the two patterns you now have: the constant table creates one runtime value (UserRole) holding members, while the literal union creates no value at all — there is no Direction table, only a rule the checker enforces about which strings fit. Descriptive, self-documenting values with zero runtime cost make literal unions the go-to enum style in Luau code.
Challenge
EasyCreate a literal union type named Direction with the members "up", "down", "left" and "right".
Create four variables, each annotated with Direction:
upDirection="up"downDirection="down"leftDirection="left"rightDirection="right"
Print, each on its own line:
upDirectiondownDirectionleftDirectionrightDirection- the message
The player moves left, built with string interpolation fromleftDirection
Try it yourself
-- Write code here
-- 1) define type Direction as a union of the four string literals
-- 2) create the four annotated variables
-- 3) print each one, then the interpolated message
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 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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps