Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

6 comments

0

you need to give context. infinite loops aren't necessarily bad; there's an occasion for everything

0

What kind of context do you need? Do you need more of the script?

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.

0

You can probably replace the whole loop with a return.

0

Ok, thank you!

2 answers

✓ Accepted answer

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

1 comment

0

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.