Recap: Generic Functions
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 62 of 73.
Challenge
MediumCombine generic aliases and generic functions in one program.
Define a generic type alias named Pair with two type parameters T and U, describing a table with:
firstof typeTsecondof typeU
Create a generic function named makePair that declares T and U, accepts first: T and second: U, and returns them packed into a Pair<T, U>.
Create a generic function named describePair that declares T and U, accepts a pair: Pair<T, U>, and returns the string ({first}, {second}) built with string interpolation (return type string).
Then:
- create
playerScoreof typePair<string, number>by callingmakePair("Nova", 87) - create
levelDoneof typePair<number, boolean>by callingmakePair(3, true) - print
playerScore.first - print
playerScore.second - print
describePair(playerScore) - print
describePair(levelDone) - print
describePair(makePair("Luau", 2026))in a single line
Try it yourself
-- Write code here
-- 1) define type Pair<T, U> = {first: T, second: U}
-- 2) define makePair<T, U>(first: T, second: U): Pair<T, U>
-- 3) define describePair<T, U>(pair: Pair<T, U>): string
-- returning `({pair.first}, {pair.second})`
-- 4) build playerScore ("Nova", 87) and levelDone (3, true),
-- then print the five required lines
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: 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 Functions