Menu
CoddyTech

Variadic Functions

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 29 of 80.

You've used Lua's ... (varargs) to write functions that accept any number of arguments. Luau lets you type the varargs, so every argument that flows in is checked:

function sum(...: number): number
    local total = 0
    for _, n in ipairs({...}) do
        total = total + n
    end
    return total
end

print(sum(1, 2))           -- 3
print(sum(1, 2, 3, 4, 5))  -- 15

...: number declares that every extra argument must be a number: sum(1, "two") becomes a type error. The runtime tools are the ones you know:

  • {...} collects the varargs into an array (here a {number})
  • select("#", ...) counts how many arguments arrived
  • ... can be passed straight through to another function, e.g. math.max(...)

As in Lua, ... must be the last parameter: regular (typed) parameters come first, the variadic tail collects the rest:

function joinWords(separator: string, ...: string): string
    return table.concat({...}, separator)
end

print(joinWords("-", "a", "b", "c"))  -- a-b-c
challenge icon

Challenge

Easy

Write two functions that take any number of arguments.

  1. Write local function sumAll(...: number): number that adds up {...} with ipairs.
  2. Write local function joinWords(separator: string, ...: string): string that returns table.concat({...}, separator).
  3. Print sumAll(5, 10, 15) and joinWords("-", "apple", "banana", "cherry").

Press Run Code: the output shows 30 and apple-banana-cherry.

Try it yourself

-- 1) sumAll(...: number): number
-- 2) joinWords(separator: string, ...: string): string
-- 3) print the two results

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler