Menu
CoddyTech

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 editing

A 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 up

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

Challenge

Easy

Store a direction that can only be one of four names.

  1. Write type Direction = "up" | "down" | "left" | "right".
  2. Declare local facing: Direction = "left".
  3. 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

Practice on your own: Online Luau compiler