If i click a button, it starts a loop, if i click again, it stops

Hello,

What im trying to do is the following:

If i click a button, it starts a “While true do” loop.

If i click again, it stops the loop.

Anyone that can help?

4 Likes

use events to control a variable; this variable will be used as the loop condition. You may need an outer while true do loop so that the inner loop runs more than once. As with all infinite loops, make sure to use a yeilding function like task.wait or event:Wait() so other code may run

local run_loop = false

button.Activated:Connect(function()
    run_loop = not run_loop
end)

-- run forever
while true do
    -- run while toggled on
    while run_loop do
         print("hello world!")
         task.wait(1)
    end
    button.Activated:Wait() -- wait for another click
end
3 Likes

Gotta find the global for button.
But yea your script will work


local run_loop = false
local button = script.Parent.Button --  Button name
button.Activated:Connect(function()
    run_loop = not run_loop
end)

-- run forever
while true do
    -- run while toggled on
    while run_loop do
         print("hello world!")
         task.wait(1)
    end
    button.Activated:Wait() -- wait for another click
end

@rukucii dont forget to mark @gertkeno ’s post as solution, if this works.

2 Likes

nevermind don’t use this method, its bad.

A thing about this is that the loop will have to completely finish before stopping. However, If you don’t want that, you can use task.spawn and task.cancel to immediately stop the loop.

Going off of other posts here:

local loopConnection = nil
local toggled = false
local button = script.Parent.Button --  Button name

button.Activated:Connect(function()
	if not toggled then --start
		toggled = true
		loopConnection = task.spawn(function()
			while true do
				print("hello world!")
				task.wait(1)
			end
		end)
	else --stop
		toggled = false
		if loopConnection then
			task.cancel(loopConnection)
			loopConnection = nil
		end
	end
end)

Hope this works for you!

2 Likes

I would highly recommend against this

threads in luau do not actually run at the same time. One thread has control and runs until it yeilds (task.wait(1)) or completes, then other threads can run. In theory task.cancel will never interrupt the while loop until task.wait(1) futhermore canceling tasks with roblox’s yeilding functions gets weirder because they step in and out of the thread, they may be marked as not running when you try to cancel it and error.

I am also pretty sure task.spawn cannot be called with :Disconnect

2 Likes

Dang, alright. Looks like I’ll have to rewrite some of my own code :sweat_smile:

And you were obviously right about :Disconnect(), that was an error on my part.

2 Likes

Maybe try using a boolean to check when the action is permitted

2 Likes