Codectionary / Developer documentation / Luau

Functions, optional arguments and returns

Functions group a calculation or action behind a named boundary. Optional types allow nil; they do not supply defaults. Return tuples and variadic arguments are useful when the number of values matters, but named record results are often easier to extend.

Syntax

local function greet(name: string?): string
    return "Hello, " .. (name or "visitor")
end

Examples

Default only when absent

Standalone Luau or a Script in ServerScriptService. Passing zero must keep zero, while omitting the argument uses one. The return annotation describes both results.

local function batchSize(requested: number?): (number, boolean)
    local size = if requested == nil then 1 else requested
    return size, size > 0
end
local size, usable = batchSize(0)
print(size, usable) -- 0, false

Collect variadic numbers

The ... parameter accepts any number of numbers. Here they are collected into a dense array, then summed. This technique is for non-nil numeric arguments, not preserving arbitrary argument lists with holes.

local function sum(...: number): number
    local total = 0
    for _, value in ipairs({...}) do
        total += value
    end
    return total
end
print(sum(2, 3, 4)) -- 9

Best practices

  • Make defaults explicit inside the function.
  • Capture all needed return values at the call site; assigning to one local discards the rest.
  • Keep validation at public boundaries rather than repeating it in every internal helper.

At a glance

Purpose
Typed scripting and Roblox development
File extension
.luau
Runs in
Luau host; Roblox engine examples require Roblox Studio
Usually used with
Roblox APIs and Studio

Specifications & further reading

Related Luau documentation