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?
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?
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
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.
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!
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
Dang, alright. Looks like I’ll have to rewrite some of my own code
And you were obviously right about :Disconnect(), that was an error on my part.
Maybe try using a boolean to check when the action is permitted