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

do too many while true do loops lag the game?

title. cant figure out another way to constantly check something.

4 answers

✓ Accepted answer

I do not understand the situation. However, yes, while loops or for loops do lag the game. Why, well this deals with Big O. Basically, code takes up space and time. To run a for loop you in behind the scenes for loops instantiate variables, then constantly check to see the variables being updated, then it runs the code in the body, and keeps doing this. This is why it takes time and space. Because you are putting in memory the local variable in a for loop then the code keeps checking if the variable is updating. While True has no condition just that it is true. So, this lags the game because it is constantly checking for a condition that will always be true. This takes up space and time. These are behind the scenes things that happen.

To constantly check something I would do a While True then inside have a conditional and a break if that condition is met. It really depends on the situation. I would advise if you can find a way not to use while loops or for loops that way is better because loops do take up space and time. Do not use too many for loops and while loop because simple code is always better than complex ones.

Instead of using:

while true do
	print("doing this lags the game")
end

Try using:

while wait() do 
	print("no lag")
end

If you put "wait()" instead of "true" in the statement, it allows the game to have a 1-tick rest period between each time the loop is run, reducing lag greatly. You will also get to avoid the "Execution time exhausted" error.

3 comments

0

I did not know this. I just started scripting. My first language was python.

0

However, I do think it still lags the game because wait still does take up space... maybe time? Again I do not know lua.

0

wait() greatly reduces the lag, since it adds a small delay and lets the place to process it.

yes, they do lag the game. while wait() do or while true do wait() also do lag the game, though if you use 1 or 2 inside of your game, you shouldn't experience major lag issues.

2 comments

0

It can lag the game significantly if the scripter has spaghetti code.

0

For example, having a nested for loops can make it super complex. Idk, if you can even do nested for loops in lua. Ima start learning the language tho.

This discussion is preserved as it was. New answers, comments, and votes are closed.