When a reference to an object is created, a signal is created, and there is an error in the same scope, the object will never be garbage collected even after all other references are removed. If the signal is not created in the same scope, there is no error, or the signal is disconnected, the object will be garbage collected as expected.
Example code causing a memory leak:
function BadFunction()
local Object = Objects[Number - 1]
local Tool = Instance.new("Tool")
Tool.Equipped:Connect(function() end)
error("Called bad function")
end
Example code that does not cause a memory leak:
function GoodFunction()
local Object = Objects[Number - 1]
local Tool = Instance.new("Tool")
Tool.Equipped:Connect(function() end)
print("Called good function")
end
function GoodFunction2()
local Object = Objects[Number - 1]
do
local Tool = Instance.new("Tool")
Tool.Equipped:Connect(function() end)
end
error("Called good function")
end
function GoodFunction3()
local _,Error = pcall(function()
local Object = Objects[Number - 1]
local Tool = Instance.new("Tool")
Tool.Equipped:Connect(function() end)
error("Called good function")
end)
error(Error)
end
Demo Video: https://cdn.bloxynet.xyz/5XQoNEDPpP43.mp4
Reproduction File:
MemoryLeak.rbxl (61.3 KB)
Expected behavior
I expect any objects that my code does not actively reference to be garbage collected.