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-cChallenge
EasyCreate 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:
sumAll(5, 10, 15)sumAll(1, 2, 3, 4, 5)countValues("a", "b", "c", "d")joinWords("-", "apple", "banana", "cherry")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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps