Menu
Coddy logo textTech

A Generic Identity Function

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

Here's the identity function done right — as a generic function:

local function identity<T>(value: T): T
    return value
end

The <T> after the function name declares a type parameter — a placeholder that stands for "some type, decided at each call". Inside the signature you use T exactly like a real type: the parameter is a T, and the function returns a T.

Using the same T for input and output is the whole trick — it ties them together. Call identity("hello") and the checker decides T = string for that call, so the result is a string. Call identity(42) and T = number, so the result is a number. One body, every type, nothing lost.

T is only a conventional name (short for "Type") — <Item> or <Value> work just as well. And as always in Luau, the angle brackets exist for the checker only: at runtime this is the plain Lua function function identity(value) return value end.

challenge icon

Challenge

Easy

Create a generic function named identity that:

  • declares a type parameter T
  • accepts one parameter named value of type T
  • returns that value, with return type T

Then create these typed variables using your function:

  • luckyNumber of type number — call identity with 7
  • greeting of type string — call identity with "Hello, Luau!"
  • isReady of type boolean — call identity with true

Print the following, each on its own line:

  1. luckyNumber
  2. greeting
  3. isReady
  4. the result of calling identity with "generics" directly inside print
  5. the result of calling identity with 99 directly inside print

Try it yourself

-- Write code here
-- 1) define identity<T>(value: T): T
-- 2) create luckyNumber, greeting and isReady with identity calls
-- 3) print them, then print identity("generics") and identity(99)
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