Script seemingly skipping over line of code?

I’m running the following code on RunService.Heartbeat;

function ParryLoop(step)
  if count < limit and parried == false then
  	count = count + step		
  else
  	print("HCS_Client | Parry phase ended. PARRYLOOP")
  	connection:Disconnect()
  end
end

Up until the print, everything works fine, however once I do reach the print, it will skips over the connection:Disconnect and straight back to the print, as shown in this GIF of me using Step In & Step Out to go through line by line.

Without the break, it looks like this. (On contact with the Dummy, the player receives an event that changes parried to true.)

connection is defined at the start of the script, just as local connection without any value. I then have connection = RunService.Heartbeat:Connect(ParryLoop) in a function to begin the Loop, which is supposed to end itself but obviously does not.

Putting another print after the Disconnect means that the script does actually go over the line, but the Disconnect still doesn’t fire. I use the exact same method elsewhere in the same script and it works fine in every other case.

This issue does not happen every time on contact with the Dummy, but completely breaks the script when it does.

I have absolutely no clue what could be causing this, I’ve asked around in a few Discord servers but no solution yet :confused:

My best guess is that the connection is being created and assigned twice, before the loop can break itself. Something like this:

-- Something has started a parry
connection = RunService.Heartbeat:Connect(ParryLoop)

-- ParryLoop is still running

-- Something starts another parry while the first loop is still running
connection = RunService.Heartbeat:Connect(ParryLoop)

-- The first ParryLoop ends
connection:Disconnect() -- disconnects the second, newer connection

-- The first ParryLoop is still at the end and repeatedly tries to disconnect the second connection
connection:Disconnect() connection:Disconnect() ...

There are two fixes:

  • Don’t allow starting a parry (creating that connection) while one is in progress
  • Keep a reference to the connection for each parry, as such:
function startParry()
	local count -- = ?
	local connection = RunService.Heartbeat:Connect(function(step) -- always creates a new anonymous function - slimy, but what can you do
		if count < limit and parried == false then
			count = count + step
		else
			print("HCS_Client | Parry phase ended. PARRYLOOP")
			connection:Disconnect()
		end
	end)
end