How do I make a while loop iterate again if the condition has changed? Thanks
You could try always running it and have the operator inside:
local number = 1
while wait() do
if number == 1 then
print("Running Code")
-- You would put more code here
end
end
I do not promote while wait() do loops, the loop doesn’t necessarily need to run all the time.
This is because we got better options like detecting the change using an event like Instance | Roblox Creator Documentation then doing something on change.
Only when you can’t use events you can go for a while wait loop.
You need to check the condition whenever its changed, then loop again.
Something like this
local foo = function(bool)
while bool do
break
end
end
local bool = true
bool = false
foo(bool)
bool = true
foo(bool)
This is another way that might be a bit better correct me if I am wrong
local looping = script.boolValue
looping.Chanaged:Connect(function()
while looping == true then
wait()
--More Code here
end
end)
local isRunning = true
while isRunning do
end
just make it so isRunning is false if it aint running and its true if it is
*if you are asking cause u wanna know how to stop a recursive function just do break instead
Yep just a few changes:
local looping = script.boolValue
looping.Changed:Connect(function()
if not looping.Value == true then
return --only concerned with bool property being true
end
while looping.Value == true then
--More Code here
--Somewhere in this code the loop value will become false breaking the while loop, job is done
looping.Value = false
end
end)
Edit: here is an example that maintains at least 10 parts in workspace, if not it’ll respawn the part with a BANG.
Edit 2: perfect @JayO_X your scenario is similar to this one. Check it out! Just copy and paste into a server script in workspace.
I am making a coin script that will start spawning if total coins are under 30. Once it reaches 30 parts or the condition is false then the loop will stop running. It is a problem because if a player collects a coin it won’t respawn or the loop won’t continue.
I know everybody knows this but for people who don’t know how to stop a loop here’s an example:
local test = false
while true do
test = not test
if test == true then
break
end
end
not a good example-
local coins = 0
local last = tick()
game:GetService("RunService").Heartbeat:Connect(function()
if tick()-last >= 1 and coins < 30 then
coins = coins + 1
-- spawn coin
end
end)
something like this perhaps?