Menu
Coddy logo textTech

The Problem Generics Solve

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

Imagine you need a function that simply returns whatever value you pass to it — an identity function. With the types you know so far, you have two options, and both hurt.

Option one: write a separate copy per type. The bodies are identical; only the annotations differ:

local function echoNumber(value: number): number
    return value
end

local function echoString(value: string): string
    return value
end

Every new type means another copy, and a bug fixed in one must be fixed in all of them. That's exactly the duplication you write functions to avoid.

Option two: collapse them into one function typed with any:

local function echo(value: any): any
    return value
end

Now one function handles everything — but you've paid with type safety. When you call echo("hello"), the checker no longer knows the result is a string. It only knows any, so autocomplete goes dark and type errors slip through: the connection between what went in and what comes out is lost.

What you really want is a function that works for every type and remembers which type each call used. That is precisely what generics give you — and they're the subject of this chapter.

Try it yourself

This lesson doesn't include a code challenge.

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