Variadic functions in Lua

Lua has a nice ability to create functions with dynamic number of arguments. Here is an example with use for that:

function FindMax(...) -- … here means that the number of arguments is dynamic
  local arguments = {...} -- takes variable number of arguments and creates table
  local max = ... -- takes only first value of passed parameters
  for i = 1, #arguments do -- #arguments is LENGTH of the arguments table
    if arguments[i] > max then
      max = arguments[i]
  return max
answer = FindMax(1,5,3,7,29,43,2,34,2);
print(answer) -- 43 in this case

Sure this one is just a proof of concept example, but its nice to know that this exists.

Leave a Reply

Your email address will not be published. Required fields are marked *