So, i'm trying to make a loop that starts when you click a button but, when you click that button again it stops. If you can help thanks!
ToggleButton.MouseButton1Click:Connect(function() --like the code here but I just can't think of anything that will make a --toggle able loop end)
EDIT: Kind of solved.. gonna be practicing the examples that LordDragonZord told me
You most commonly see them written as while true do
. They loop until the condition is not true
(false
or nil
). When the condition is not met, it'll break automatically.
--Loops until the condition is not true. while true do --True will always be true; loops forever print("Hi") wait(1) end local a, b = 10, 13 while a < b do --Breaks once a is greater than b. a = a+1 b = b+0.5 end
A coroutine is basically like creating a whole new script inside your script. That way, if you have any yields in your coroutine, it doesn't affect the rest of your script and the coroutine yields independent of whatever is going on in the rest of your actual script. How to make a coroutine:
local CountDown = coroutine.wrap(function() for i = 10,0,-1 do print("Countdown: "..i) wait(1) end end) CountDown() wait(3) print("Interruption :D")
Countdown: 10 Countdown: 9 Countdown: 8 Interruption :D Countdown: 7 ...
There are 2 waits in the script. Neither of them interrupt each other.
local activated = false local MyLoop = coroutine.wrap(function() activated = not activated --If false, it's now true (and vise versa) while activated do --Your Code Here wait(1) --A wait is necessary when you are looping many times. end end) ToggleButton.MouseButton1Click:Connect(function() MyLoop() --Calls the coroutine end)
Hope it helps!
Here's an idea I came up with.
local CanLoop = false ToggleButton.MouseButton1Click:Connect(function() if CanLoop then CanLoop = false else CanLoop = true end end) while true do wait() if CanLoop then print("loop running") end end
To toggle anything ever. A two way toggle, there is this cool thing called a "Boolean" This boolean is a true or false value which can change depending on what you tell it to do.
To create a loop in an event depending on a bool, try this out!
local a = true ToggleButton.MouseButton1Click:Connect(function() repeat wait() -- run code if a == true then -- you can make it false or run other code while a is true. -- if you insert a = false here then the loop stops. end until a == false end)
If this helped, click the Answer Button C: Goodbye!