Menu
Coddy logo textTech

Literal Types

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 33 of 73.

Types like string allow any string — but sometimes only a few exact values make sense. A literal type uses the value itself as the type:

local mode: "dark" = "dark"   -- only the string "dark" is allowed
local locked: true = true      -- only the boolean true is allowed

On their own, single-value types are a curiosity. Combined with unions, they become one of Luau's most useful tools — a strictly controlled set of allowed values:

type Direction = "north" | "south" | "east" | "west"
type GameState = "menu" | "playing" | "paused" | "gameover"

local move: Direction = "north"     -- ✓
local state: GameState = "playing"  -- ✓
-- local bad: Direction = "diagonal" -- ✗ type error!

Now a typo like "nort" or an invalid value like "diagonal" is caught while you edit — with a plain string it would sail through and break at runtime, if you're lucky enough to notice.

Literal types are case-sensitive and exact: "North" doesn't match "north". String literals are the common case, but boolean and (in newer Luau versions) number literals work the same way. This pattern — a union of string literals — is also how Luau replaces other languages' enums, as you'll see in a later chapter.

challenge icon

Challenge

Easy

Create three literal-union type aliases:

  • Direction = "north" | "south" | "east" | "west"
  • GameState = "menu" | "playing" | "paused" | "gameover"
  • Difficulty = "easy" | "medium" | "hard"

Declare, using the aliases:

  • playerDirection: Direction = "north"
  • currentState: GameState = "playing"
  • selectedDifficulty: Difficulty = "medium"

Create a function movePlayer(direction: Direction): string returning "Moving [direction]", and a function updateGameState(state: GameState): string returning "Game state: [state]".

Print, each on its own line:

  1. movePlayer(playerDirection)
  2. updateGameState(currentState)
  3. the value of selectedDifficulty

Try it yourself

-- Write code here
-- type Direction / GameState / Difficulty as literal unions
-- declare playerDirection, currentState, selectedDifficulty
-- movePlayer(direction: Direction): string -> "Moving [direction]"
-- updateGameState(state: GameState): string -> "Game state: [state]"
-- print the three results
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