I am not familiar with protecting against memory leaks although I understand the concept. I disconnect my events and everything when I need to. However, I was recently creating a custom loading screen and then realized I don’t actually know if what I’m doing at the end will cause a memory leak. So this is basically my code:
local Gui = script.Parent
-- Other code for preloading and stuff
Gui:Destroy() -- Called as the last line after I've disconnected two events I use.
My question is this: Will destroying the gui (and as a result, its descendants, including the local script) cause all the variables and connections declared in the local script to be garbage collected? I would think it would but I don’t actually know and I can’t find anywhere on the devforum stating this.
As far as I know, script instances only serve to contain/hold the script and provide it a shortcut directory for its functions (the script global). Deleting the script instance won’t terminate the script that’s executed in it, the script will have to terminate itself either by reaching the end or ending a loop.
Thank you. I decided to test what you said with two test.
Test #1:
-- This tested if the script would run and finish executing without the script instance. The result was that it would.
script:Destroy()
for i=0,500 do
print("Test")
task.wait()
end
Test #2:
-- This tested if the connections in the script would be disconnected when the script instance was destroyed. The result was they would.
workspace.ChildRemoved:Connect(function(child : Instance)
print(child.Name," Removed")
end)
workspace:FindFirstChild("Part"):Destroy()
task.wait()
script:Destroy()
workspace:FindFirstChild("Part"):Destroy()