Menu
Coddy logo textTech

Using Literal Union Enums

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 54 of 73.

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. The :: cast you learned earlier tells it to treat the value as your enum type:

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

Create the literal union type Direction with members "up", "down", "left" and "right".

Create a function move that takes direction: Direction and prints Moving [direction]...

Create a function getMovementDescription that takes direction: Direction, returns a string, and handles every member with if/elseif/else:

  • "up"Going upward
  • "down"Going downward
  • "left"Turning left
  • "right"Turning right

Read one line from the user with io.read() and cast it to Direction with ::. Then:

  1. call move with the direction
  2. print the result of getMovementDescription for the same direction

Try it yourself

-- Write code here
-- 1) define type Direction
-- 2) write move and getMovementDescription (if/elseif/else)
-- 3) read the input: local direction = io.read() :: Direction
-- 4) call move, then print the description
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

Practice on your own: Online Lua compiler