Generic Arrays
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 60 of 73.
Generics get really useful once tables are involved. You already write typed arrays as {number} or {string} — inside a generic function the element type can simply be T, and {T} means "an array of whatever T turns out to be".
Here's the classic example — fetching the first element of any array:
local function first<T>(items: {T}): T?
return items[1]
endPass a {string} and the checker infers T = string, so the result is a string. Pass a {number} and it's a number. One function replaces a whole family of per-type copies.
Look closely at the return type: it's T?, not T. An array can be empty, and then items[1] is nil — the optional type you met earlier says so honestly: "a T, or nil". The checker will nudge callers to handle the nil case before using the result, which is exactly the bug-catching you want from a typed language.
Challenge
EasyCreate a generic function named first that:
- declares a type parameter
T - accepts one parameter named
itemsof type{T} - returns the first element, with return type
T?(it'snilfor an empty array)
Create these typed arrays:
fruitsof type{string}with"apple","banana","cherry"scoresof type{number}with10,20,30,40flagsof type{boolean}withfalse,trueemptyof type{string}with no elements
Print the result of calling first with each array, in that order, each on its own line.
Try it yourself
-- Write code here
-- 1) define first<T>(items: {T}): T? returning items[1]
-- 2) create fruits: {string}, scores: {number}, flags: {boolean},
-- and an empty {string} array
-- 3) print first(...) of each array, in that order
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 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