As a Roblox developer, it is currently too hard to create multiple functions that take unique type signatures with the same name.
If Roblox is able to address this issue, it would improve my development experience, because I would be able to make simpler modules, functions, scripts, etc.
Egregious Example
As we all know, most of the functions we use (CFrame.new(6 methods), ColorSequence.new(3 methods), etc.), has multiple methods of constructing a value:
When constructing a CFrame, we can choose to have either:
- Empty, just a 0, 0, 0 CFrame
- 1 Vector3 (position)
- 3 numbers as a Vector3 position
- 2 Vector3 (position, lookAt)
- 5th method I don’t really understand (Probably something to do with position and rotation)
- A method to construct a CFrame with all the “matrixes”
Now, what I suggest, is to add a feature, where you can make a constructor that takes unique combinations of arguments, as multiple methods. Basically, function overloading.
function foobar(a: number, b: Vector3): string
return "I got a number and a Vector3!"
end
-- As of now, this just prints an error, telling us that we overwrote a function.
function foobar(a: Vector3): string
return "I got a Vector3!"
end
function foobar(a: nil): string
return "I got nothing. :("
end
print(foobar(Vector3.new(5, 15, 7))) -- "I got a Vector3!"
print(foobar(7, Vector3.new(62, 13, 5))) -- "I got a number and a Vector3!"
print(foobar()) -- "I got nothing. :("
This is in fact possible with a normal function, but this isn’t very feasible to do so.
function foobar(a, b)
if typeof(a) == "number" and typeof(b) == "Vector3" then
return "I got a number and a Vector3!"
elseif typeof(a) == "Vector3" then
return "I got a Vector3!"
end
return "I got nothing. :("
end
print(foobar(Vector3.new(5, 15, 7))) -- "I got a Vector3!"
print(foobar(7, Vector3.new(62, 13, 5))) -- "I got a number and a Vector3!"
print(foobar()) -- "I got nothing. :("
Module Example
local module = {}
function module:GetSomething(a: Vector3): Vector3
return a * Vector3.new(5, 2, 1.5)
end
function module:GetSomething(a: number): string
return "Your number is " .. tostring(a) .. "."
end
function module:GetSomething(a: nil): string
return "I think you forgot to insert an argument..."
end
return module
Use cases:
- Simpler, yet more effective modules
- Easier organization in scripting
Here’s a wiki page more about function overloading.