Generic Arrays
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 64 of 80.
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
EasyGet the first element of any array.
- Write
local function first<T>(items: {T}): T?that returnsitems[1]. - Declare
local fruits: {string} = {"apple", "banana"}andlocal empty: {number} = {}. - Print
first(fruits), thenfirst(empty).
Press Run Code: the output shows apple and nil.
Try it yourself
-- 1) first<T>(items: {T}): T?
-- 2) fruits: {string} and an empty {number}
-- 3) print first of each
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