Menu
Coddy logo textTech

Variadic Functions

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 27 of 73.

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

Create a function named sumAll that takes any number of number arguments (...: number) and returns their sum as a number.

Create a function named countValues that takes any number of string arguments and returns how many were passed, as a number — use select("#", ...).

Create a function named joinWords that takes a required separator: string followed by any number of string arguments, and returns them joined with the separator (use table.concat on {...}) — return type string.

Call and print, each on its own line:

  1. sumAll(5, 10, 15)
  2. sumAll(1, 2, 3, 4, 5)
  3. countValues("a", "b", "c", "d")
  4. joinWords("-", "apple", "banana", "cherry")
  5. joinWords(" | ", "red", "green", "blue")

Try it yourself

-- Write code here
-- sumAll(...: number): number       -- loop over {...}
-- countValues(...: string): number  -- select("#", ...)
-- joinWords(separator: string, ...: string): string
-- then print the five results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau