I want to break a while loop in one script from another script.
I don’t know how to do it.
I was thinking of adding a condition in a loop, checking a variable that if true, will break the loop from the inside scope, so I could then change that variable from another script.
But that’s busy-waiting and I want it to be more event-based, so like, a function that I call that breaks the loop, maybe?
But a function outside of a loop can’t break the loop even if it is in the same script, which is why I’m stuck.
You could maybe do this with a variable, also I don’t think using a BoolValue would use too much resources. As function names also count as variables, you can just set it to nil and use an if statement to check if the function still exists.
local function Loop()
print("Hi")
end
task.delay(5, function() -- Instead of delaying use your event
Loop = nil
end)
while task.wait(1) do
if Loop then
Loop()
else
break
end
end
_G.BreakMode = false -- BoolValue
local function A()
repeat
--repeat what
if BreakMode == false and SomeLogicHere then
_G.BreakMode = true
break -- if you want to break this too
end
until
-- until what
end
In another script:
local function B()
repeat
--repeating something
if _G.BreakMode == true then
print"Function A said to break myself"
break
until
---Something running nonstop or whatever
end
just an exampl,e, maybe there is some other way to do that
You can use bindable events, which can trigger it easily with Event:Fire
--//Script with loop
local running = true
local break_loop = Instance.new('BindableEvent') do --//"do" is for organizational purposes
break_loop.Name = 'BreakLoop'
break_loop.Parent = script
break_loop.Event = function()
running = false
end
end
while running and task.wait() do --//Checks if "running" is true, and waits about 1/40 seconds
--//loopy
end
--//Script without loop
local script = game.ServerScriptService:FindFirstChild('LoopyScript') --//Script with loop in it
local break_loop = script:WaitForChild('BreakLoop')
break_loop:Fire() --//Breaking the loop
Make sure to name the event something specific when you make a new one, so you don’t have a ton of “BreakLoop” events in one instance, because that would sure be confusing!