Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you halt a loop in a function?

I apologize for no script since I feel that it would be more confusing. Below is a summary. Thanks.

I have a button that when activated, the local script inside the button communicates with a script in the ServerScriptService using a Remote Event and function x is ran. There’s a while loop in function x. When I press another button, I want to make the loop in function x stop and run function y which has a while loop in the same script.

1 comment

0

You need a condition to make the loop stop. Try restructuring your code.

2 answers

✓ Accepted answer

so i think i get it. you want to switch the loop currently executing when you press the button? in this case you could have two remote events for each button, and then have two variables in the script defining if loop A or loop B should be running:

loopA = false	-- defines if loop A should be running
loopB = false	-- defines if loop B should be running

remote_event1.OnServerEvent:Connect(funciton()	-- when the first button is pressed...
	loopA = true
end)

remote_event2.OnserverEvent:Connect(function()	-- when the second button is pressed...
	loopA = false
	loopB = true
end)

while true do
	if loopA then	-- if loop A's got to be running...
		-- action
	end
	if loopB then	-- if loop B's got to be running...
		-- action
	end
end

You can base the while loops of a condition, that way they'll break through a Boolean switch. You'll have to be careful about running a loop within a function, as it is a yield function, meaning it won't let the code below run, or allow you to activate any functions below. You can solve this by spawning a separate thread for the loop to run on via the spawn() function.

local LoopCondition = false

local function x()
	while not (LoopCondition) do
		--// Code
	wait() end
end

local function y()
	while (LoopCondition) do
		--// Code
	wait() end
end

spawn(x)
wait(5); LoopCondition = true--// Stops loop x
spawn(y)
wait(5); LoopCondition = false--// Stops loop x

This discussion is preserved as it was. New answers, comments, and votes are closed.