Menu
Coddy logo textTech

The never Type

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

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)
end

error() 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 icon

Challenge

Easy

Build a small calculator that fails loudly on bad input.

  • Write fail(message: string): never that calls error(message, 0).
  • Write handleOperation(operation: string, value: number): number that returns value * 2 for "double", value / 2 for "half", and otherwise calls fail with Invalid operation: [operation].
  • Write tryOperation(operation: string, value: number) that calls handleOperation through pcall: print the result on success, or Error: [message] on failure.

Run these five calls in order:

  1. tryOperation("double", 5)
  2. tryOperation("half", 8)
  3. tryOperation("triple", 3)
  4. tryOperation("double", 15)
  5. tryOperation("half", 20)

Try it yourself

-- Write code here
-- 1) fail(message: string): never  — use error(message, 0)
-- 2) handleOperation(operation: string, value: number): number
-- 3) tryOperation: pcall(handleOperation, ...), print result or "Error: ..."
-- 4) run the five test calls from the task
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