I have been using EventListeners a lot, and when I added one that listens for roundEnd broadcast to a weapon, it was still called even after the weapon is destroyed.
Looking through the Core API documentation for event listener, there is one example.
I feel that it raises more questions.
function OnResourceChanged(player, resName, resValue) print("Resource " .. resName .. " = " .. resValue) end local resourceChangedListener = nil function OnPlayerJoined(player) if player == Game.GetLocalPlayer() then resourceChangedListener = player.resourceChangedEvent:Connect(OnResourceChanged) end end if Game.GetLocalPlayer() then OnPlayerJoined(Game.GetLocalPlayer()) else Game.playerJoinedEvent:Connect(OnPlayerJoined) end function OnDestroyed(obj) if resourceChangedListener and resourceChangedListener.isConnected then resourceChangedListener:Disconnect() resourceChangedListener = nil end end script.destroyEvent:Connect(OnDestroyed)
From what I can see so far, memory leaks happen when broadcaster is still there, but the script containing the listener is destroyed.
- Is the reference to the listener kept by the broadcaster keeping the listener from getting garbage colllected?
- Are we setting the variable holding the listener to nil because this is still a reference that prevents garbage collection? Does this not get freed automatically when the script is destroyed and the variable goes out of scope?
- What about for the opposite direction of a more permanent script listening to broadcast of a transient object? When the object is deleted and this listener disconnected, would the listener be garbage collected if we never saved it to a variable?
- In terms of a very commonly used function, Game.playerJoinedEvent, why do the client script never disconnect this listener? When the player leaves wouldn't this listener be left there?
- What about the existence of a onDestroy listener itself? Presumably this is a script that exists longer than the object. Should this listener also be disconnected and set to nil when it is executed?
- Is there any big downsides (outside of maybe performance) to not just have script:OnDestroyed listener for everything?