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 allowedOn 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
EasyAllow only four exact direction names.
- Write
type Direction = "north" | "south" | "east" | "west". - Write
local function movePlayer(direction: Direction): stringreturning`Moving {direction}`. - Declare
local playerDirection: Direction = "east"and printmovePlayer(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
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler