Menu
Coddy logo textTech

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

Create 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:

  1. upDirection
  2. downDirection
  3. leftDirection
  4. rightDirection
  5. the message The player moves left, built with string interpolation from leftDirection

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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau