TExcelTAD
Home › Lua › Lua Varargs

Lua Varargs

A variadic function accepts any number of arguments. In Lua you write three dots ... as the last parameter; inside the function, ... stands for the extra arguments.

lua · try it yourself
local function sum(...)
  local total = 0
  for _, v in ipairs({ ... }) do
    total = total + v
  end
  return total
end

print(sum(1, 2, 3))
print(sum(10, 20, 30, 40, 50))
print(sum())
6
150
0

{ ... } collects the arguments into a table so you can loop over them.

Using ... directly

... behaves like a multiple-return call: in the last position it expands to all values, so you can pass them on:

lua · try it yourself
local function log(level, ...)
  print("[" .. level .. "]", ...)
end

log("INFO", "server started on port", 8080)
log("WARN", "disk usage", 91, "%")

local function first(...)
  local a = ...          -- one variable takes the first value
  return a
end
print(first("x", "y", "z"))
[INFO]	server started on port	8080
[WARN]	disk usage	91	%
x

Counting arguments and the nil problem

#{ ... } is unreliable when some arguments are nil (a table with holes has no well-defined length). Use select("#", ...) to count, and select(i, ...) to fetch:

lua · try it yourself
local function countArgs(...)
  return select("#", ...)
end

print(countArgs())
print(countArgs(nil, nil))
print(countArgs(1, nil, 3))

local function describeAll(...)
  for i = 1, select("#", ...) do
    local v = (select(i, ...))
    print(i, v, type(v))
  end
end
describeAll("a", nil, false)
0
2
3
1	a	string
2	nil	nil
3	false	boolean

select(i, ...) returns the i-th value and all after it; the parentheses keep only the first.

table.pack and table.unpack

table.pack(...) stores the arguments plus a field n with the true count. table.unpack(t [, i [, j]]) does the opposite: it spreads a table into separate values:

lua · try it yourself
local function packed(...)
  local args = table.pack(...)
  return args.n, args[1], args[args.n]
end
print(packed("first", nil, "last"))

local point = { 3, 4 }
local function distance(x, y) return math.sqrt(x * x + y * y) end
print(distance(table.unpack(point)))

print(table.unpack({ "a", "b", "c", "d" }, 2, 3))
3	first	last
5.0
b	c

Wrapping functions

Varargs make it easy to write a function that wraps another without knowing its parameters. Here is a small "call counter" that works with any function:

lua · try it yourself
local function counted(fn)
  local calls = 0
  local wrapper = function(...)
    calls = calls + 1
    return fn(...)
  end
  local function getCount() return calls end
  return wrapper, getCount
end

local countedMax, maxCalls = counted(math.max)
print(countedMax(3, 9, 4))
print(countedMax(-1, -5))
print("math.max was called " .. maxCalls() .. " times")
9
-1
math.max was called 2 times

return fn(...) passes every argument through and returns every result. This also uses a closure (calls is remembered between calls), the topic of the next lesson.

Common mistakes

Mistake Problem Fix
#{...} with nil arguments length is undefined with holes select("#", ...)
using ... inside a nested function ... belongs to the function that declares it; a nested function can't see it copy it first: local args = table.pack(...)
... not last in the parameter list syntax error put ... last

Test yourself

How do you count the arguments passed through ..., including nil ones?

  1. #...
  2. #{...}
  3. select("#", ...)
  4. count(...)

What does table.unpack({1, 2, 3}) return?

  1. A table
  2. The three values 1, 2, 3
  3. The number 3
  4. The string "1,2,3"

What does table.pack("a", nil).n return?

  1. 1
  2. 2
  3. nil
  4. An error