I was messing with modules to understand what circumstances can cause memory leak but this really confused me

I created 2 scripts and one module script.

module script:

local connection

local module = {}

function module.function2()
	while task.wait(.1) do
		print(connection)
	end
end

function module.function1()
	

	connection = game:GetService("RunService").Heartbeat:Connect(function()
		print("aaaaaaa")
	end)
	local ticka = tick()
	spawn(function()

		while task.wait(.1) do
			print("connection 2:")
			print(connection)
			
			if tick() - ticka > 25 then
				print("15 seconds")
				print(connection)
				if connection then
					connection:Disconnect()
					connection = nil
					print("DISCONNECTED")
					print(connection)
				else
					print("no connection")
				end
			end
			
		end

	end)
	wait(7)
	print("bb")
	return connection
end

return module

server scripts:

local module = require(game.ReplicatedStorage.ModuleScript)
local connection = module.function1()
print(123)
print(connection)

wait(10)
warn("connection disconnecting")
connection:Disconnect()
connection = nil
print(connection)
local module = require(game.ReplicatedStorage.ModuleScript)
module.function2()

so in first 10 seconds, heartbeat function runs, it prints “aaaaaaa”, prints “Connection” in modules as expected

after 10 seconds the heartbeat connection gets disconnected in first server script (the script returns the connection while calling module to disconnect again) and prints connection as nil as it should be. but the thing is that the module script keep printing connection as “Connection” even though the connection is disconnected

so i added some part inside the module that connection is created to disconnect connection in the module and it started printing connection as nil (it says 15 seconds in output i forgot to change it)


so what happened here? why the module kept printing connection after the first script disconnected it?

Does this occur if you don’t require the module twice?

i deleted the second script and yeah, its same

You seem to misunderstand what disconnecting a connection does.

It does prevent the connected function from running when the event is fired.
It does not set all references to it to nil.

You are disconnecting the the connection in your normal script, and then you set the reference in that same script to nil, however the reference stored inside the module script is still there, which is what is printed when you call function2.

This isn’t a memory leak, as this can only ever result in a single unused reference, however if you want to resolve it, you need to set the variable in the module to nil as well.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.