3

# Does Lua support OverLoading functions? (Two identically named functions with different parameters)

Necrorave 560
8 years ago

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

--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.

7

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

print(one+two+three)
end

--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


0
Ah, yes. I get my terms mixed up a lot. I will fix the title. Thanks for the answer, too. Necrorave 560 — 8y
3
The reason Lua doesn't allow type-based overloading is Lua variables do not have types. You can use Tables to sort functions with the same names but different numbers or types of parameters, though. adark 5487 — 8y
0
6
BlueTaslem 18071
8 years ago

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