Hey guys, I was wondering if Lua or Roblox supports the idea of having multiple functions with the same name but different parameters.
Example:
function add(one, two) --Code end function add(one, two, three) --Code end
Using the above example, would I be able to call one of the functions depending on the amount of parameters I pass?
Lets say I call add(1, 1)
would that then call the first function properly?
Same thing goes for add(1, 1, 2)
?
If there is a link to this, let me know. I was looking but I could not find it.
I believe you meant to say overloading and not overriding and the answer is no. Lua believes that the function is being redefined and will only use the most recently defined function.
Example:
function add(one, two) print(one+two) end function add(one, two, three) print(one+two+three) end print(add(5,3)) --input:6: attempt to perform arithmetic on a nil value (local 'three')
However, there is an easy work-around to this. You can set default values by using a quick relational operation.
function add(one, two, three) three = three or 0; print(one+two+three) end
However, with multiple inputs, the solution mentioned above may seem annoying. A last solution could be execution based on inputs:
function add(one, two) if type(one) == "string" && type(two) == "number" then print(one..two) elseif type(one) == "number" && type(two) == "number" then print(one+two) end end
But in summary, Lua doesn't allow type-based overloading.
DigitalVeer's answer is correct. Because parameters don't have types, and because function declarations are assignments, overloading isn't possible.
A related concept, variadic functions, however, are possible. A variadic function is one that can take any number of parameters.
An example in Lua is math.min
.
You can write variadic functions in Lua using ...
as the name of a parameter to the function. Then, ...
is a tuple of all of the arguments. Usually this is most usefully handled by immediately dumping it into a table.
For example, here is a variadic definition of add
:
function add(...) local t = {...} local sum = t[1] for i = 2, #t do sum = sum + t[i] end return sum end print( add(1) ) -- 1 print( add(1, 2, 3) ) -- 6 print( add( Vector3.new(1,1,1), Vector3.new(5, 0, 0), Vector3.new(4, 0, 0), Vector3.new(0,0,-1) ) ) -- 10, 1, 0
For your example, this is what you want -- variadic functions, not overloading (though overloading definitely has its uses, it's unfortunately not directly possible in Lua since Lua is not typed)