Lesson 10 of 15

Variadic Functions

Variadic Functions

Lua functions can accept a variable number of arguments using ...:

function sum(...)
  local total = 0
  local n = select("#", ...)
  -- select("#", ...) returns the number of arguments
  return total
end

The ... collects all arguments. A simple way to work with variadic arguments is to pass them directly to other functions:

function printAll(...)
  print(...)   -- passes all args to print
end

Combining Fixed and Variadic Parameters

function greetAll(greeting, name1, name2)
  print(greeting .. ", " .. name1 .. "!")
  print(greeting .. ", " .. name2 .. "!")
end

Your Task

Write three functions: add3 that adds three numbers, mul3 that multiplies three, and sub that subtracts.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.