Debounce function module seems to be mixing up local variables

I have a debounce function which is similar to the one on the wiki:

return function(f)
    local db = false
    return function(hit)
        if (db) then return end
        db = true

        f(hit)
        db = false
    end
end

I’ve also set up many other modules relying on this code, doing a ton of different behaviours. Most of the time, it’s fine; but recently it’s been getting mixed up, firing off other functions once one of them gets called.

For example, I’m setting up two of them such that:

function touchA() print("Touched A") end
function touchB() print("Touched B") end

partA.Touched:Connect(debounce(touchA))
partB.Touched:Connect(debounce(touchB))

And for some reason, when players touch Part A, even though it mostly fires off touchA, it sometimes fires off touchB. Likewise, touching Part B will sometimes fire off touchB.

I’ve been using the module for at least a year in various games and have never experienced this issue with it. It’s only been the last few days that it’s happened.

The way I’ve gone about “patching” it is to detect if they’re actually within range of the part, but that’s kind of an awful solution. I’m just wondering, is this an issue in my code or did I find a problem with the new VM?

Edit: Some actual code from my game, using the debounce function above:


	self._ring.Touched:Connect(debounce(function(hit)
		local player = PlayerFromTouch(hit)
		if (not player) then return end
		
        self:_activateQuest(player)
	end))
self._teleporter.Touched:connect(debounce(function(hit)
		local player = playerFromTouch(hit)
		if (not player) then return end
		
		self:_teleport(player)
	end))

The first one deals with a quest system that I have; the second are the teleporters I have for my game. When I touch the ring for quests, I’ve been teleported away; I’ve seen notifications for other events in my game; etc.

Just a clarification — is the function posted above the code that is in your game, or just an example you pulled off the wiki?

1 Like

It’s an example I recreated from the wiki, but my actual code is the same:

function debounce (f)
	local db = false
	local func = f
	return function (...)
		if (db) then return end
		db = true
		
		func (...);
		
		db = false
	end
end

return debounce;

The only difference is the local func = f, but I only added that after it started having those problems (one of my attempts to see if I could find a workaround). Both forms have the same problem with it

Now that I think about it, it’s probably useful to see some actual code I’ve written for the game using the debounce system. I’ve included that (an edit in the post). Thanks!