How do you do work with while loops?

while wait() do
    if ((p1 - p2).Magnitude <= 100) then
        break
    end
end

instead of in the correct manner:

while (p1 - p2).Magnitude > 100 do
    wait()
end

I saw this here: While-Wait-Do Idiom - Google Docs
But, It’s quite, weird.
The way I’ll do it it’s like this.

local run = true
while (true) do
if (not run) then
break
end
if (check here)
end
end

What’s best way with working with while loops?
memory tho.

The second one is best. The difference in memory probably isn’t that significant but the first example is a little redundant with the if-then-break statement and the third is just confusing to look at.

Whenever you have something like:

while (true) do
	if (condition) then
		break
	end
	someCode()
end

It can almost always be replaced with:

while (not condition) do
	someCode()
end

The two are equivalent.

1 Like

What do you mean is the best?
as far as I know, while loops have impacts in memory.

You can reduce memory usage by moving certain things outside the loop (like variable declarations, etc.) but those are just micro-optimizations.

1 Like