I've heard on numerous occasions that using while true do loops are bad, so how can I replace this script?
if script.Parent.TotalAmmo.Value <= 0 then
while true do
wait(999999999)
end
end
I've heard on numerous occasions that using while true do loops are bad, so how can I replace this script?
if script.Parent.TotalAmmo.Value <= 0 then
while true do
wait(999999999)
end
end
while true do loops aren't necessarily bad, and are actually very commonly used among other programming languages.
However, one thing to note is that in Roblox, you must include a wait() inside non-terminating loops or your game will freeze (known as a hang). This is due to Roblox's task scheduler and how it invokes every function in succession, and if a function doesn't return or doesn't include some kind of yielding (like wait), it won't be able to make a full loop. And thus, cannot render the next frame until it does [which is never].
Ok, thanks!
One alternative to a while true do infinite loop is the RenderStepped function:
game:GetService("RunService").RenderStepped:Connect(function()
print(workspace.Part.CFrame.LookVector) --it will print the direction "Part" is pointing every tick
end)
This is a good alternative when trying to constantly check for certain values and update other values throughout the time that the game is running.
This discussion is preserved as it was. New answers, comments, and votes are closed.
6 comments
you need to give context. infinite loops aren't necessarily bad; there's an occasion for everything
What kind of context do you need? Do you need more of the script?
Considering 999999999 seconds is almost 32 years, I don't think you need the
whileloop. However, there's still almost certainly a better way to do what you're doing. Please post the rest of the script.https://pastebin.com/jS73bC9b
You can probably replace the whole loop with a
return.Ok, thank you!