🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Varargs

Varargs are the extra arguments a function accepts when the exact count is not fixed in advance. A function written with ... can take any number of arguments in one call.

Counting arguments with select

count asks select for the number of arguments it received. Two calls with different counts print 2 and then 5.

local function count(...)
  print(select("#", ...))
end

count(10, 20)
count(1, 2, 3, 4, 5)

Packing varargs into a table

sum packs its arguments with {...} and loops over the table. The three packed numbers add up to 12.

local function sum(...)
  local nums = {...}
  local total = 0
  for i, v in ipairs(nums) do
    total = total + v
  end
  return total
end

print(sum(3, 4, 5))

Picking the first vararg

first returns what select(1, ...) starts with. Capturing that single result keeps 9, the first of the three values passed.

local function first(...)
  return select(1, ...)
end

local picked = first(9, 8, 7)
print(picked)

Example

local function average(...)
  local nums = {...}
  local total = 0
  for i, v in ipairs(nums) do
    total = total + v
  end
  return total / #nums
end

print(string.format("%.1f", average(10, 20, 30, 40)))

Key points

  • Dots: three dots, written ..., stand in the definition where the changing arguments arrive.
  • Pack: {...} collects all the passed arguments into a table.
  • Count: select("#", ...) returns how many arguments were passed.
  • Pick: select(2, ...) returns values starting from the second argument.
  • Calls: the same varargs function can be called with two arguments in one call and five in the next.

In this example, average packs its four arguments into a table and adds them up to 100. Dividing by the table length, 4, gives 25.0, and string.format prints it with one decimal place.

Note

varargs is short for variable arguments, meaning the count can change from call to call.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A function countArgs(...) returns select("#", ...). What does print(countArgs("a", "b", "c")) print?