Codectionary / Developer documentation / Luau

Luau generic functions

A generic function relates its input and output types without replacing them with any. A reusable first-element helper can preserve the array element type while accounting for empty input.

Syntax

local function first<T>(items: {T}): T?

Examples

Luau generic functions

Run as a standalone current Luau script, or as a Script in Roblox Studio ServerScriptService. No Roblox engine APIs are required; type-annotated syntax is not standard Lua.

--!strict
local function first<T>(items: {T}): T?
    return items[1]
end
local names: {string} = {"Ada", "Lin"}
local name = first(names)
if name ~= nil then print(string.upper(name)) end
print(first({} :: {number}) == nil)
  1. Output: ADA, then true. The first call returns string? while the empty numeric array returns nil.

Best practices

  • Keep relationships between type parameters meaningful. Generic annotations do not validate arbitrary data at runtime.

Runtime & versions

Luau host; Roblox engine examples require Roblox Studio. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Luau documentation

Specifications & further reading