String Enums as Unions
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 57 of 80.
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
EasyStore a direction that can only be one of four names.
- Write
type Direction = "up" | "down" | "left" | "right". - Declare
local facing: Direction = "left". - Print
facing, then`The player moves {facing}`.
Press Run Code: the output shows left and The player moves left.
Try it yourself
-- 1) type Direction as a union of four strings
-- 2) local facing: Direction = "left"
-- 3) print facing, then the sentence
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