Menu
Coddy logo textTech

Arrays Genéricos

Parte da seção Introdução ao Luau do Journey de Lua da Coddy — lição 60 de 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

Desafio

Fácil

Crie uma função genérica chamada first que:

  • declara um parâmetro de tipo T
  • aceita um parâmetro chamado items do tipo {T}
  • retorna o primeiro elemento, com o tipo de retorno T?nil para um array vazio)

Crie estes arrays tipados:

  • fruits do tipo {string} com "apple", "banana", "cherry"
  • scores do tipo {number} com 10, 20, 30, 40
  • flags do tipo {boolean} com false, true
  • empty do tipo {string} sem elementos

Imprima o resultado de chamar first com cada array, nessa ordem, cada um em sua própria linha.

Experimente você mesmo

-- Escreva o código aqui
-- 1) defina first<T>(items: {T}): T? retornando items[1]
-- 2) crie fruits: {string}, scores: {number}, flags: {boolean},
--    e um array {string} vazio
-- 3) imprima first(...) de cada array, nessa ordem
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Introdução ao Luau