Menu
CoddyTech

Literal Types

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

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

Allow only four exact direction names.

  1. Write type Direction = "north" | "south" | "east" | "west".
  2. Write local function movePlayer(direction: Direction): string returning `Moving {direction}`.
  3. Declare local playerDirection: Direction = "east" and print movePlayer(playerDirection).

Press Run Code: the output shows Moving east.

Try it yourself

-- 1) type Direction = "north" | "south" | "east" | "west"
-- 2) movePlayer(direction: Direction): string
-- 3) local playerDirection: Direction = "east", then print the move

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler