Will this cause a memory leak?

I’m wondering will this cause a memory leak.

local t = {Load = Humanoid:LoadAnimation(Animation)}

function Stop(KeyName)
	t[KeyName].Load:Stop()
	t[KeyName] = nil
end

local ref = t.Load

ref.Stopped:Connect(function()
	print("Animation stopped!")
	Stop("Load")
	print(ref.Load) -- is not nil
end)

The function stop has set the value to nil but the defined variable ref remains the same, will this cause a memory leak?

1 Like

probably wont cause a memory leak but maybe some memory related issues

1 Like

ref continues to reference the animation, and ref is referenced in the listener to ref.Stopped, so refdoesn’t get GC’ed and so the animation doesn’t get GC’ed either.

But it’s not really a leak. It’s just a single reference and a single Animation object that doesn’t get cleaned up. It doesn’t grow over time, so it never causes an issue.

If you really want ref and the animation to get cleaned up, you can try something like this:

When the connection gets disconnected, it doesn’t have to reference the closure you passed, so ref isn’t referenced anywhere and it can get cleaned up automatically when/if its scope is exited. According to his post it might not.

Calling Stop in a Stopped event will cause an infinite stop loop. Wouldn’t it already have stopped whenever that event is fired?

Well this is just an example, let’s suppose that we use “KeyframeReached” which makes more sense in this case.

The connection does not grow but it hangs in the memory for forever unless ref is being set to nil, am I correct?
So what if instead of using ref, I use t.load? It will be something like:

t.load.Stopped:Connect(function()
	print("Animation stopped!")
	Stop("Load")
end)

The function stop will set t.load to nil, so it will also disconnect the connections of it. So comparing this to binding t.load to a variable ref, this does not hang the connection in the memory since the connection was built on t.load instead of a new variable, am I correct?