Menu
CoddyTech

A Generic Identity Function

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 62 of 80.

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

Write one function that returns any value with its type intact.

  1. Write local function identity<T>(value: T): T that returns value.
  2. Declare local luckyNumber: number = identity(7) and local greeting: string = identity("Hello, Luau!").
  3. Print luckyNumber, then greeting.

Press Run Code: the output shows 7 and Hello, Luau!.

Try it yourself

-- 1) identity<T>(value: T): T
-- 2) luckyNumber and greeting from identity calls
-- 3) print both

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler