← Back to Lua Course | Chapter 5: Functions | Lesson 3 of 7

Variable arguments

Three dots let a function accept any number of arguments.

In this page:

  1. Variable arguments

Variable arguments

A function declared with ... in its parameter list is variadic. Inside it, ... is an expression list, and select("#", ...) gives the count while select(n, ...) returns arguments from position n onward. table.pack(...) or {...} collects them into a table. The count from select is correct even when some arguments are nil.

Note: Use table.pack(...) instead of {...} when arguments can be nil, because it records n.

Example: Variable arguments

lua
local function sum(...)
  local total = 0
  for _, v in ipairs({...}) do total = total + v end
  return total
end
print(sum(1, 2, 3, 4))

local function count(...)
  return select("#", ...)
end
print(count(), count(nil, nil), count(1, 2, 3))
print(select(2, "a", "b", "c"))
print(select(-1, "a", "b", "c"))

-- Output:
-- 10
-- 0	2	3
-- b	c
-- c
Common Mistakes
  1. Using {...} and trusting # when nil values are passed
  2. Trying to index ... directly
  3. Forgetting that ... is only valid inside a vararg function
Chapter Summary
  • ... makes a function variadic
  • select("#", ...) counts arguments
  • select(n, ...) skips to n
  • table.pack keeps nils safe with n

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.