Menu
CoddyTech

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

Write a helper that never returns, and catch its error.

  1. Write local function fail(message: string): never that calls error(message, 0).
  2. Write local function half(value: number): number that calls fail("Odd number") when value % 2 == 1, otherwise returns value / 2.
  3. Print half(8), then pcall(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

Practice on your own: Online Luau compiler