Variable number of arguments in Lua Programming


There are functions in Lua that accept a variable number of arguments. These are very helpful in cases where we want to run the same function with many different arguments that might vary in length. So, instead of creating a different function, we pass them in a variable arguments fashion.

Syntax

function add(...)
   -- function code
end

It should be noted that the three dots (...) in the parameter list indicate that the function has a variable number of arguments. Whenever this function will be called, all its arguments will be collected in a single table, which the function addresses as a hidden parameter named arg.

Example

Now let’s consider an example where we will pass variable number of arguments to a function. The function will be used to calculate the minimum value present in the array that was passed to it as an argument. Also, it will be used to find the minimum values index and we will print both the minimum value and the minimum index.

function minimumvalue (...)
   local mi = 1 -- maximum index
   local m = 100 -- maximum value
   local args = {...}
   for i,val in ipairs(args) do
      if val < m then
         mi = i
         m = val
      end
   end
   return m, mi
end

print(minimumvalue(8,10,23,12,5))

Output

5   5

Notice that now we can make use of the fact that we can have a variable number of arguments in the same function, and hence, when we call the same function again, we will get the minimum value and the minimum index.

Example

function minimumvalue (...)
   local mi = 1 -- maximum index
   local m = 100 -- maximum value
   local args = {...}
   for i,val in ipairs(args) do
      if val < m then
         mi = i
         m = val
      end
   end
   return m, mi
end

print(minimumvalue(8,10,23,12,5))

print(minimumvalue(1,2,3))

Output

5   5
1   1

Updated on: 01-Dec-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements