The never Type
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 76 of 80.
Every type describes a set of possible values: boolean has two, number has many. never is the type with no values at all: it marks places in the code that cannot produce a value, because they cannot happen.
Its most common use is as the return type of a function that never returns normally: one that always raises an error, or loops forever:
local function fail(message: string): never
error(message, 0)
enderror() stops execution on the spot (you know it from Lua). The second argument 0 keeps the message clean, without it, Lua prefixes the script name and line number. A caller can trap the error with pcall, which returns false plus the message instead of crashing. Note how never differs from a function with no return values: a () function finishes and hands control back; a never function never reaches its own end.
never also shows up in contradictory narrowing. If value is a string and you test typeof(value) == "number", the branch can't ever run: inside it, the checker gives value the type never: no value could possibly be both. Seeing never in a hover or an error message is the checker telling you "this situation is impossible".
Challenge
EasyWrite a helper that never returns, and catch its error.
- Write
local function fail(message: string): neverthat callserror(message, 0). - Write
local function half(value: number): numberthat callsfail("Odd number")whenvalue % 2 == 1, otherwise returnsvalue / 2. - Print
half(8), thenpcall(half, 3).
Press Run Code: the output shows 4, then false and Odd number on one line.
Try it yourself
-- 1) fail(message: string): never, using error(message, 0)
-- 2) half(value: number): number
-- 3) print half(8), then pcall(half, 3)
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