Recap: Generic Functions
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 66 of 80.
Challenge
MediumPack two values of different types into one pair.
- Write
type Pair<T, U> = {first: T, second: U}. - Write
local function makePair<T, U>(first: T, second: U): Pair<T, U>returning{first = first, second = second}. - Store
makePair("Nova", 87)inlocal playerScore: Pair<string, number>and print`({playerScore.first}, {playerScore.second})`.
Press Run Code: the output shows (Nova, 87).
Try it yourself
-- 1) type Pair<T, U> = {first: T, second: U}
-- 2) makePair<T, U>(first: T, second: U): Pair<T, U>
-- 3) playerScore from makePair("Nova", 87), then print it
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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