The Enum Pattern in Luau
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 55 of 80.
Programs are full of values drawn from a small, fixed set: an order is pending, shipped or delivered; a player faces up, down, left or right. Many languages have an enum keyword for this. Luau does not, and it doesn't need one, because two tools you already own cover the job.
Pattern 1: the constant table. A plain table maps meaningful names to values, replacing "magic numbers" scattered through the code:
local Status = {
Pending = 1,
Active = 2,
Done = 3,
}
print(Status.Active) -- 2This is a real runtime value: you can read Status.Active, compare against it, and pass it around, just like the tables you've used all along.
Pattern 2: the literal union. A type made of exact string values, using the literal types you met in the unions chapter:
type Color = "red" | "green" | "blue"
local favorite: Color = "green" -- ✓
local oops: Color = "yellow" -- ✗ type errorThe union exists only for the checker, zero runtime cost, but it guarantees a variable can hold nothing outside the set. The two patterns complement each other: the table gives you runtime values under one name; the union gives you a compile-time guarantee. Later in this chapter you'll also meet table.freeze, which protects a constant table from being modified at runtime.
Challenge
EasyTry both enum patterns side by side.
- Create the constant table
local Speed = {Slow = 8, Fast = 24}. - Write
type Pace = "slow" | "fast"and declarelocal pace: Pace = "fast". - Print
Speed.Fast, thenpace.
Press Run Code: the output shows 24 and fast.
Try it yourself
-- 1) a constant table Speed with Slow = 8, Fast = 24
-- 2) type Pace = "slow" | "fast", then local pace: Pace = "fast"
-- 3) print Speed.Fast, then pace
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