Loop not breaking

I have a sword that when a key is being held it will heal the player for the duration of the time (Status: true)
Then when the key is let go it will stop healing (Status: false)

But I cannot add the heal player part yet with this problem:
The problem is the loop continues and it still thinks ifHeal equals true

Ability.SwordHeal = function(player, ifHeal)
	print("Status:", ifHeal)
	
	while task.wait() do
		local Heal = ifHeal
		print("looping", Heal)
		if Heal == false then
			print("stopped")
			break
		end
	end
	print("Double Check Status:", ifHeal)
end

image

I have also tried repeat until but the same problem happens

Ability.SwordHeal = function(player, ifHeal)
	print(tostring("Status: "..ifHeal))
	
	while task.wait() do
		local Heal = ifHeal
		print(tostring("Looping "..Heal))
		if Heal == false then return break end
		end
	end
	print(tostring("Double Check Status: "..ifHeal))
end

That should work.

Is heal a Boolean value? (Like a Boolean instance.)

Yes, it is
And with the code reply, there are some red lines
image

If it’s an actual instance (Like an IntValue, but Boolean instead), then try this:

Ability.SwordHeal = function(player, ifHeal)
	
	while task.wait() do
		local Heal = ifHeal
		if Heal == false then break end
		end
	end
end

That may work.

Added a couple of prints to your code to check anything and the problem persists
It still somehow continues even when it detects its false

Couldn’t you just simply do

Ability.SwordHeal = function(Player, Healing)

	while Healing do 
		task.wait()
	end
end

loop still continues
(gotta reach the char requirement)

The problem isn’t really how OP is writing the while loop, it’s how they’re setting up the flag that should end it. What they, as well as proposed solutions don’t realise, is that when the function is called again with different arguments it’s not going to stop the original while loop that was going.

You need to handle this differently. SwordHeal should be dependent on a variable outside of the function, or better yet the while loop shouldn’t be started by SwordHeal (because in that case, you’re going to end up with n while loops where n represents every player that can call this function). SwordHeal should just flag which players should be actively healing when its called and then an outside for loop should be running over all actively healing players and giving health.

1 Like

Fixed it after searching a little more and finding a post from 2018
Just need to simply move the variable… (hours wasted)

Thank you for helping out though
Need to check if it works with other players though (edit it does!)

local Heal = false

Ability.SwordHeal = function(player, ifHeal)	
	Heal = ifHeal

	while Heal == true do
		task.wait(0.5)
		print("looping")
		if Heal == false then
			print("breaked")
			break
		end
	end
	print("stopped")
	Heal = false
end
1 Like