Menu
CoddyTech

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

Get the first element of any array.

  1. Write local function first<T>(items: {T}): T? that returns items[1].
  2. Declare local fruits: {string} = {"apple", "banana"} and local empty: {number} = {}.
  3. Print first(fruits), then first(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

Practice on your own: Online Luau compiler