How do you break a loop if an else statement is met?

i’ve left a comment in the code. I have no clue how to do this.
code:

local power = workspace.Technical.PowerValue
local pconsumption = workspace.Technical.PowerConsumptionValue
local light = workspace.Technical.LeftLight.SpotLight
local lightsound = light.Parent.LightSound
local on = false
script.Parent.MouseClick:Connect(function()
	if not on then
		if power.Value >= 0 then
			on = true
			light.Enabled = true
			lightsound:Play()
			pconsumption.Value -= 2
			while task.wait(pconsumption.Value) do
				power.Value -=1
				if power.Value == -1 then
					break
				end
			end
		end
	else
		if power.Value >= 0 then
			on = false
			light.Enabled = false
			lightsound:StopPlay()
			pconsumption.Value += 2
			--where i want the original loop to break
		end
	end
end)

There is no loop in this code, is there…?

Although I’m not sure what your specific situation is because I can’t tell exactly what you’re trying to do, consider using methods such as break, return or a boolean value to achieve this.

while task.wait(pconsumption.Value) do
				power.Value -=1
				if power.Value == -1 then
					break
				end

it is in the code.

Add another variable, let’s call it canLoop, change the loop code to:

while task.wait(pconsumption.Value) do
	power.Value -=1
	if power.Value == -1 or not canLoop then
		break
	end

and simply change canLoop to false.

1 Like

Ah, I see.

You could do this with a boolean value using the break method.

local power = workspace.Technical.PowerValue
local pconsumption = workspace.Technical.PowerConsumptionValue
local light = workspace.Technical.LeftLight.SpotLight
local lightsound = light.Parent.LightSound
local on = false
script.Parent.MouseClick:Connect(function()
local enabled = true
	if not on then
		if power.Value >= 0 then
			on = true
			light.Enabled = true
			lightsound:Play()
			pconsumption.Value -= 2
			while task.wait(pconsumption.Value) do
				if not enabled then break end
				power.Value -=1
				if power.Value == -1 then
					break
				end
			end
		end
	else
		if power.Value >= 0 then
			on = false
			light.Enabled = false
			lightsound:StopPlay()
			pconsumption.Value += 2
			enabled = false -- sets enabled to false causing loop to break
		end
	end
end)

I’ve realized that… while loops just check if a condition is met and then do the thing. So i could’ve checked the on bool.

Edit: this code just sucks lol don’t sample it

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.