Is there a way to break out of a loop outside the loop?

Here’s what I mean… I’m trying to make a hammer that has to be charged before being able to be swung. And while Activated, force would charge up so the longer you charge, the stronger the knock back would be.

local tool = script.Parent
local remoteEvent = tool.RemoteEvent
local force = 0

tool.Activated:Connect(function()
	for i = 0, 1000 do
		force = i
		wait()
	end
end)

tool.Deactivated:Connect(function()
	--maybe break here?
	remoteEvent:FireServer(force)
end)

I think some sort of debounce can be used but I just don’t know how to execute it. Please help, thanks much! <3

You could have a variable down, set it to false at first, then in the tool.Activated event listener set it to true first thing. Then in the tool.Deactivated event listener, set it to false. Then in your loop check if down went false.

So this makes your code something like

local tool = script.Parent
local remoteEvent = tool.RemoteEvent
local force = 0
local down = false

tool.Activated:Connect(function()
	down = true

	for i = 0, 1000 do
		if not down then
			break
		end

		force = i
		wait()
	end
end)

tool.Deactivated:Connect(function()
	down = false
	remoteEvent:FireServer(force)
end)
2 Likes

just realised someone else sent the answer already. But anyways this is how it’s done!

local tool = script.Parent
local remoteEvent = tool.RemoteEvent
local force = 0
local charging = true
tool.Activated:Connect(function()
charging = true
	for i = 0, 1000 do
if charging == true then
		force = i
		wait()
else
i=999
	end
end)

tool.Deactivated:Connect(function()
	charging = false
	remoteEvent:FireServer(force)
end)
1 Like

You should just be using the break keyword instead of setting i to the maximum loop value

Not to mention that wouldn’t even work, since i = 999 is just setting a “copy” of the variable to that number.

2 Likes

oh yes we can do that, but anyways the output would be the same. But yes you’re right the preferred method is using a break statement.