Event to break loop

Goal: break the function “a” with an outside event like touched.

If you try making an event to break the loop, it will only break the event’s function,
therefore this would not work.

local part = script.Parent
local b = false

local function a ()
	part.Touched:Connect(function()
		return
	end)
	for i = 0, 100 do
		wait(1)
		if b == true then
			return
		end
	end
end

Solution, but not exact mechanics wanted.

local part = script.Parent
local b = false

local function a ()
	for i = 0, 100 do
		wait(1)
		if b == true then
			return
		end
	end
end


part.Touched:Connect(function()
	b = true
end)

a()

Let’s say the function “a” will be run, and the function “a” could be called every second to 0.01th of a second. I want an event that ends all current “a” functions but will not stop future “a” functions. The reason I thought about events is I want it to be as fast as possible.

put the part.Touched function before function a

make sure b is set to false some time after it is called or else future function a’s will not run

This should work. You probably won’t get exactly the code you want, especially because it’s not practical to use the touched event inside of the loop.

local part = script.Parent
local b = false

part.Touched:Connect(function(hit)
	if  hit.Parent:FindFirstChild("Humanoid") then
		b = true
	end
end)

local function a()
	for i = 0, 100 do
		task.wait(1)

		if b then
			return
		end
	end
end

a()
1 Like

Just solved my own solution.
Giving each “a” function its own variable tracker.

Ill give ya the solution checkmark cause you tried!

local part = script.Parent

local function a ()
	local b = false
	part.Touched:Connect(function()
		b = true
	end)
	for i = 0, 100 do
		wait(1)
		if b == true then
			return
		end
		print(i)
	end
end




a()

wait(5)

a()
3 Likes
local Workspace = workspace
local Part = Workspace.Part

local function OnTouched(Connection)
	Connection:Disconnect()
end

local function Init()
	local Connection
	Connection = Part.Touched:Connect(function() OnTouched(Connection) end)
	
	for _ = 0, 10 do
		if not Connection.Connected then break end
		print("Hello world!")
		task.wait(1)
	end
end

for _ = 1, 10 do
	Init()
	task.wait(1)
end