Is it possible to use Function Overloading in Lua?

I know that there are some solutions to Function Overloading like middleclass and that random forum post on the lua-forum. But is there a better way to implement this? I haven’t found a way to do this without installing the biggest library ever to use one of its functions.
Something like this:

function Data.Open(Name,Player)
    --Find store from name and index player
end

function Data.Open(Store,Player)
    --Already have the store and index player
end

function Data.Open(StoreID,Player)
    --Find store from ID and index player
end

Im making a DataModule and figured it would be beneficial to have something of the sort without doing a bunch of checking and obfuscating my code.

1 Like

Yes. You can typecast your function using & for function overloading.

--!strict

local module = {}

module.foo = function(a: any, b: any): ()
	if typeof(a) ~= typeof(b) then
		error(`invalid argument(s)`, 2)
	end
	
	-- code
end :: ((a: string, b: string) -> ()) & ((a: number, b: number) -> ())

module.foo(1, 2)
module.foo("a", "b")
-- type error
module.foo(1, "b")
-- type error
module.foo("a", 2)

return module
5 Likes

I’ve never seen typecasting before. This changes a lot for me. I figured out how it works now and thank you for the message and are experimenting more with typecasting.
Heres what I have now:

Data.Open = function(Name : any,Player : any)
    if typeof(Name) ~= typeof(Player) then
		error(`invalid argument(s)`, 2)
	end
    --Code to open DataStore
end :: ((Name: string, Player: {}) -> ()) & ((Name: string, Player: number) -> ())

Data.Open("Bob", {"Player Object"}) -- Good
Data.Open("Bob", 123) -- Good
Data.Open("Bob", "Bobs ID") -- Not Good

Type casting is definitly a fun way to play with functions.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.