So after doing some experimenting I figured out that script signals a.k.a events have “owners”.
If the following code is executed inside a ModuleScript:
local module = {}
module.event = workspace.ChildAdded:Connect(function(obj)
print(obj.Name " was added!")
end)
return module
When the module executes for the first time, the module “owns” the event, meaning that even if the script that initiated the module is Destroy()
'd, this event connection along with it’s connected function will continue to exist and function as usual.
However
If we now do this instead:
ModuleScript
local module = {}
function module.object_added(obj)
print(obj.Name " was added!")
end
function module.make_event()
module.event = workspace.ChildAdded:Connect(module.object_added)
end
return module
Script
local module = require(game.ReplicatedStorage.MyModule)
module.make_event()
This function will still execute when things are being added to workspace
, that is, until we Destroy()
this script.
After destroying it, doing print( module.event.Connected )
prints false
.
This implies or sorta indicates that the script that called the function actually owns the event connection.
Despite the function still existing in the ModuleScript
, the event is disconnected when the script that “owns” that event is destroyed.
On to the question
Is there actually a way in Roblox to know which script definitively owns an event connection?
And if so, are there ways to pass that connection around?
I figured this entire thing kinda functions like how pointers/references do.
Some things I have not tested yet is whether event connections can be passed through BindableEvents or -Functions.
This behavior is also not clearly documented in the Roblox documentations and it makes it hard to figure out how precisely it works.
My intend is to utilize this behavior and structure projects in a way such that they are safe from any potential memory leaks or lingering events.
I may have most of my code in ModuleScripts (where event connections are often also being made) and I would like to know or find a way to track which currently running script owns an event connection.