Mega Bump, but I canât make a new thread so this will have to do.
I constantly run into problems where I have to sacrifice speed and memory to create a new lambda just so I can pass some parameters through the callback.
This comes up again and again in OOP and other event-driven code. For example, since I canât pass âselfâ for the function I would have to create a lambda just to do a namecall:
function Class:OnHeartbeat(DeltaTime)
...
end
function Class:Init()
RunService.Heartbeat:Connect(function(DeltaTime)
self:OnHeartbeat(DeltaTime)
end)
end
Ugliness aside, whatâs worse is that lambda wonât cache in memory, because it uses self
as an upvalue, so it just stays in memory. If we could pass arguments through (Assuming they go before the callback args), both problems could easily be solved:
function Class:Init()
RunService.Heartbeat:Connect(self.OnHeartbeat, self)
end
Another case can be seen with chained events, such as the âPlayerAdded/CharacterAddedâ idiom. In the OnPlayerAdded
callback, we might want to pass both the Character model and the Player instance so we can use its interface, like waiting for its CharacterAppearance to load:
local function OnCharacterAdded(Player: Player, Character)
if Player.CanLoadCharacterAppearance and not Player:HasAppearanceLoaded() then
Player.CharacterAppearanceLoaded:Wait()
end
...
end
local function OnPlayerAdded(Player)
if Player.Character then
OnCharacterAdded(Player, Player.Character)
end
Player.CharacterAdded:Connect(function(Character)
OnCharacterAdded(Player, Character)
end)
end
Again, that lambda for CharacterAdded
will not be cached, keeping it in memory for the entire life of each Player (In this code, I could and have used Players/GetPlayerFromCharacter
, but this seems extraneous and obviously shows some design flaw). If we could pass Player as an arg directly, all the problems go away.
There are a multitude more situations where this implementation would help, but for the brevity of this post Iâll limit it to the two above. For the sake of better code, please engineers look into this. Thank you.