Skip to main content
  1. Posts/

Variadic Arguments in Lua

··275 words·2 mins·
Lua
Table of Contents

In Lua, to pass variable number of arguments, we can use ... (three ellipses) syntax in function argument.

Lua tutorial here tells us to use arg variable to access variadic arguments passed to functions. According to discussions here, this only works for Lua 5.0 and has been removed in Lua 5.1. See also changelog here:

  • The vararg system changed from the pseudo-argument arg with a table with the extra arguments to the vararg expression. (See compile-time option LUA_COMPAT_VARARG in luaconf.h.)

Instead, we can emulate that using the following code:

local arg = {...}

To get the number of extra arguments, we can use select('#', ...):

function my_fun(a, b, ...)
  local n = select('#', ...)
  print('num of extra arg:', n)
end

Note that when first argument to select is a number, select() will return all variable arguments starting from that index.

local v1, v2, v3, v4 = select(1, 'ab', 'b', 'c')  -- v1: 'ab', v2: 'b', v3: 'c', v4: nil
local v1, v2, v3, v4 = select(2, 'ab', 'b', 'c')  -- v1: 'b', v2: 'c', v3: nil, v4: nil
local v1, v2, v3, v4 = select(3, 'ab', 'b', 'c')  -- v1: 'c', v2: nil, v3: nil, v4: nil
local v1, v2, v3, v4 = select(4, 'ab', 'b', 'c')  -- all these variable is nil

As another example, we can calculate the sum of all arguments:

local fun = function (a, b, ...)
  local sum = 0
  sum = sum + a
  sum = sum + b
  local vararg = {...}
  for _, v in pairs(vararg) do
    sum = sum + v
  end
  return sum
end

print(fun(1, 2, 3, 4))

References
#

Related

Lua Learning Notes
··830 words·4 mins
Lua