Sign in to follow this  
Followers 0
atrX

Scripting Basics: While Loop, For Loop and Infinite Loops

1 post in this topic

What is a while loop?

A while loop will execute code as long as a condition is met.

 

How to use a while loop?

Please login or register to see this code.

 

Why use a while loop? I got for loops already!

There's a simple reason: your source code looks cleaner. Let's take a look:

Please login or register to see this code.

Honestly, which one looks more appealing to the eye? The while loop, right. Now, obviously for loops have their usage too, but if you simply need to do a conditional loop, go with a while loop.

 

What is a for loop?

A for loop will execute code as long as a condition is met. Unlike while loops, however, for loops can also declare and initialize a variable and/or execute a line of code (loop expression) inside the actual logic statement. Let's take a look:

Please login or register to see this code.

 

How to use a for loop?

As I said before, a for loop consists of 3 parts: declaration/initialization, condition and a loop expression. These 3 parts are all optional, you will often see things like:

Please login or register to see this code. Please login or register to see this code.

These are just some examples, there's way more uses for a for loop than shown here.

In general for loops are used like in the first example, meaning initialization is used to initialize a variable to check for in the condition and incremented/decremented/... in the loop expression. But there's quite a few exceptions as seen in the above examples.

 

Why use a for loop?
For loops are love, for loops are life. They honestly help make your code much more organized, let's compare a regular for loop to what it would look like when done with a while loop:

Please login or register to see this code. Please login or register to see this code.

The for loop is a lot more organised, as you can see.

 

How to make an infinite loop?
Both for and while loops can be easily made infinite:

Please login or register to see this code. Please login or register to see this code.

 

Error: Potential infinite loop, what now?

Obviously you can't physically have code running infinitely without waiting between every loop execution, if the engine would allow you to do this the game would most likely crash. Heck, it even freezes for a couple seconds now when you try to run an infinite loop without waiting between every loop execution. So, how can you solve this? The answer lies in the wait() function:

Please login or register to see this code.

Alternatively, because this is a for loop, you could do something like this:

Please login or register to see this code.

Share this post


Link to post
Share on other sites
Sign in to follow this  
Followers 0