Help with connections for touched

Basically when you press a button and stay on it i want it to give the player stats as theyre stood on the button

then when they leave the button obviously stop giving stats.

the touched event happens but it doesnt disconnect when i leave the part

Please help, unless anyone has a better idea on a way to do this

for _,Stat in Buttons:GetChildren() do
	for _,Button in Stat:GetChildren() do
		local Connection 
		Connection = Button.TouchPart.Touched:Connect(function(Char)
			Button.TouchPart.TouchEnded:Connect(function()
				Connection:Disconnect()
			end)
			while wait(0.05) do
				local suc,err = pcall(function()
					Pressing(Char,Button)
				end)
			end
		end)
	end
end

i may be wrong but i think it might work if the TouchEnded event was outside the Touched event

for _,Stat in Buttons:GetChildren() do
	for _,Button in Stat:GetChildren() do
		local Connection 
		Connection = Button.TouchPart.Touched:Connect(function(Char)
			while wait(0.05) do
				local suc,err = pcall(function()
					Pressing(Char,Button)
				end)
			end
		end)

		Button.TouchPart.TouchEnded:Connect(function()
			Connection:Disconnect()
		end)
	end
end

You are making a new while loop every time the touched event fires, and disconnecting that event from the function when it’s no longer being touched by something. So not only the player would get way more stats than normal, it won’t stop because it’s an unending while loop.

So should i do

if Connection ~= nil then return end

or something similair

Have you tried using a state machine?

for _,Stat in Buttons:GetChildren() do
	for _,Button in Stat:GetChildren() do
		local touching = false
		
		Button.TouchPart.Touched:Connect(function(hit)
		  -- do whatever you need to check if it's the player's character
		  touching = true
		end)
		
		Button.TouchPart.TouchEnded:Connect(function(hit)
		  -- do whatever you need to check if it's the player's character
		  touching = false
		end)
		
		task.spawn(function()
		  while task.wait(0.05) do
		    if touching then
		      -- increase the player's stats here
		    end
		  end
		end)
	end
end

If my knowledge about lua closures and upvalues is correct then all three of those functions should be able to access/modify the touching state, otherwise you’ll get an error something along the lines of “can’t access touching” or “out of scope”.

If this does happen, make a two-dimensional dictionary outside of the for loops that’s accessed with the keys Stat and Button, to store the states. Then, replace touching inside all three functions with that. If you’ll need to clean stuff up later, make two other dictionaries with similar structure, but to store the connections of the two events. If all the connections are disconnected at once, then just use an array. As for the while loop, you can add a condition inside that breaks it, if a boolean at the start of the script is true.