Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Since using infinite loops is bad, how can I replace this script?

Asked by 5 years ago

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
0
you need to give context. infinite loops aren't necessarily bad; there's an occasion for everything Gey4Jesus69 2705 — 5y
0
What kind of context do you need? Do you need more of the script? DaBrainlessOne 129 — 5y
0
Considering 999999999 seconds is almost 32 years, I don't think you need the `while` loop. However, there's still almost certainly a better way to do what you're doing. Please post the rest of the script. fredfishy 833 — 5y
View all comments (2 more)
0
You can probably replace the whole loop with a `return`. fredfishy 833 — 5y
0
Ok, thank you! DaBrainlessOne 129 — 5y

2 answers

Log in to vote
1
Answered by
ee0w 458 Moderation Voter
5 years ago
Edited 5 years ago

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].

0
Ok, thanks! DaBrainlessOne 129 — 5y
Ad
Log in to vote
0
Answered by
SteamG00B 1633 Moderation Voter
5 years ago

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.

Answer this question