Menu
Coddy logo textTech

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]
end

Pass 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 icon

Challenge

Easy

Create a generic function named first that:

  • declares a type parameter T
  • accepts one parameter named items of type {T}
  • returns the first element, with return type T? (it's nil for an empty array)

Create these typed arrays:

  • fruits of type {string} with "apple", "banana", "cherry"
  • scores of type {number} with 10, 20, 30, 40
  • flags of type {boolean} with false, true
  • empty of 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau