What are variadic functions? Well for a beginner, it is a function which can support any numbers of provided arguments.
This exist because Lua is built from C and C has variadic functions
Well to put simply, let me just show you an example
function variadic(...) --... is a symbol to represent one or more arguments
return ...
end
print(variadic(true,"hi",2)) -- true,"hi",2
But variadic are much more powerful than that.
function sum(...:number) --we added : number so that the argument should only be a number and nothing else
local sum = 0
for i,v in pairs({...} do --putting brackets around ... will turn it into a table, ... will only return a number and not a table
sum += v
end
return sum
end
print(add(1,1,1)) -- 3
print(add(1,"hi",1)) -- error
So what is this even useful for?
This can be useful for ability functions which need a specific argument
local abilities = {}
function abilities.ability1(pos)
end
function abilities.ability2(player,pos)
end
function doAbility(ability,argument)
abilities[ability](argument)
end
doAbility("ability2",player,pos) -- we need two arguments but this function only supports one argument
doAbility("ability1",pos)
We can fix this by using variadic functions
local abilities = {}
function abilities.ability1(pos)
end
function abilities.ability2(player,pos)
end
function doAbility(ability,...)
abilities[ability](...)
end
doAbility("ability2",player,pos)
doAbility("ability1",pos)
Fun Fact : I used to do this lol
--NEVER EVER DO THIS IN YOUR SCRIPTS!!!!!
local abilities = {}
function abilities.ability1(pos)
end
function abilities.ability2(player,pos)
end
function doAbility(ability,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10)
abilities[ability](arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10)
end
doAbility("ability2",player,pos)
doAbility("ability1",pos)
Conclusion
Variadic functions are very useful. They can be very helpful in making math functions which can require more than one number. It can also be helpful to provide conflicting arguments to a function.