Menu
CoddyTech

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) -- 2

This 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 error

The 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 icon

Challenge

Easy

Try both enum patterns side by side.

  1. Create the constant table local Speed = {Slow = 8, Fast = 24}.
  2. Write type Pace = "slow" | "fast" and declare local pace: Pace = "fast".
  3. Print Speed.Fast, then pace.

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

Practice on your own: Online Luau compiler