Dear new Luau developers, I’m on my knees, begging you— please stop with the makeshift function overloads. I know Luau doesn’t support overloading yet, but stitching together if
statements and type()
checks isn’t the solution. You’re not creating art; you’re creating a Frankenstein function that nobody wants to debug.
Code that I had to deal with
function Public.Get(...)
-- get player
local target,cache = ...
local player = nil
if target ~= nil then
player = type(target) == 'boolean' and Resources.LocalPlayer or target
else
player = Resources.LocalPlayer or target
end
-- [ Actual logic here, trimmed for readability reason ]
-- [ Another code to deal with the arguments, has nothing to do with what the function is supposed to do ]
if cache ~= nil and cache or (type(target) == 'boolean' and target or true) then
return local_data.save
end
Public.Update(player)
return local_data.save
end
Think of the poor soul (probably future you) who’ll have to figure out why this function acts differently.
Instead, embrace Lua’s simplicity. Use clear function names, like GetFromPlayer
and use consistent arguments that does not change behavior depending of their types. It’s not flashy, but at least your code won’t send anyone spiraling into existential despair. Thank you.
The better, more readable code
function Public.Get(cached: boolean?)
-- Don't repeat, Public.Get becomes a shortcut to GetFromPlayer for the local player
return Public.GetFromPlayer(Resources.LocalPlayer, cached)
end
function Public.GetFromPlayer(player: Player, cached: boolean?)
assert(player)
-- [ Actual logic here ]
-- [ Simpler to understand than a makeshift overload function ]
if not cached then
Public.Update(player)
end
return data.save
end