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
endThe <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
EasyWrite one function that returns any value with its type intact.
- Write
local function identity<T>(value: T): Tthat returnsvalue. - Declare
local luckyNumber: number = identity(7)andlocal greeting: string = identity("Hello, Luau!"). - Print
luckyNumber, thengreeting.
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
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and Maps6Typing Table Shapes
Inline Shape AnnotationsType Aliases for ShapesOptional PropertiesShapes vs. Loose TablesExtending ShapesAdding Methods to ShapesSelf and Colon MethodsRecap: Defining Table Shapes9Generics: A First Look
The Problem Generics SolveA Generic Identity FunctionUsing a Generic FunctionGeneric ArraysGeneric Type AliasesRecap: Generic FunctionsPractice on your own: Online Luau compiler