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-cChallenge
EasyWrite two functions that take any number of arguments.
- Write
local function sumAll(...: number): numberthat adds up{...}withipairs. - Write
local function joinWords(separator: string, ...: string): stringthat returnstable.concat({...}, separator). - Print
sumAll(5, 10, 15)andjoinWords("-", "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
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler