Menu
CoddyTech

Using Literal Union Enums

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 58 of 80.

Literal unions earn their keep as function parameters. Type a parameter with the union and the checker guarantees the function is only ever called with a valid member:

type Direction = "up" | "down" | "left" | "right"

local function move(direction: Direction)
    print(`Moving {direction}...`)
end

move("left")  -- ✓
move("north") -- ✗ type error: not a Direction

Inside the function, handle the members exhaustively with an if/elseif chain. Since the type limits the input to four values, checking three and letting else take the last one covers everything:

local function describe(direction: Direction): string
    if direction == "up" then
        return "Going upward"
    elseif direction == "down" then
        return "Going downward"
    elseif direction == "left" then
        return "Turning left"
    else
        return "Turning right"
    end
end

One wrinkle: strings arriving from outside, like io.read(), are typed as plain string, because the checker can't know what a user will type. Luau's cast operator :: fixes that: value :: Type tells the checker to treat the value as that type. The Type Assertions lesson near the end of this section covers casts in full; for now, one line is enough:

local direction = io.read() :: Direction

A cast is a promise, not a check, at runtime nothing verifies the input. Production code would validate first; here it lets typed functions accept user input cleanly.

challenge icon

Challenge

Easy

Turn a direction typed by the player into an action.

  1. Write type Direction = "up" | "down" | "left" | "right".
  2. Write local function getAction(direction: Direction): string returning "Climb", "Drop", "Turn left" or "Turn right".
  3. Read local direction = io.read() :: Direction and print getAction(direction).

Press Run Code: with the input up, the output shows Climb.

Try it yourself

-- 1) type Direction
-- 2) getAction(direction: Direction): string
-- 3) local direction = io.read() :: Direction, then print the action

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler