ID:152971
May 14 2005, 4:48 am
|
|
I was wondering when I should use loops and which one should I use.
|
Copyright © 2024 BYOND Software.
All rights reserved.
Deciding that you want a loop is simple. The more important part is choosing the correct type of loop. Loops in Byond include for, while, do-while and goto. You will probably get the most use out of for and while, and you might never use goto at all.
The for-loop is simple enough, but it has 3 different ways that it can be used. In each, the code block owned by the for-loop will execute, and a certain variable will be changed each time depending on how it is looping.
The first is as in the above code example with the jumping jacks. It simply executes with the variable incrementing from the first number to the second number.
The next version I will describe is similar, but it is used to loop through the items of a list. You use "variable in list", and the loop will go through list.len times with the variable being equal to an item in the list each time.
The last version is somewhat more complicated. This version has 3 parameters, called the initialization, the test and the increment. It has four steps.
(1)It first does whatever the initialization tells it to do.
(2)Then it checks to see if the test is true (just like in an if statement).
(3)Then it will execute the for-loop's code block if test is true.
(4)After that, it does the increment part, which is usually to do a bit of math on a variable.
It then goes back to step 2. Therefor, it repeats until test results in false.
To make that into a form of easier to understand pseudocode...
As for the while loop, that is fairly simple to understand. while has one parameter, and that is a testing one. As long as it results in true, it executes its code.
Be extra careful with while loops, as they are easy to make a mistake with which can result in an infinite loop, freezing the program.
The do-while version of the while loop is only slightly different. You put the while part after the code block, and the keyword "do" before it. The only difference is that it is sure to execute at least once.
The usefulness in that comes in situations like the following.
In that, if you used a normal while loop it would do nothing, as title starts as null and would return false in the while. However, using do-while, it is forced to execute at least once, letting the player input his/her title first before it gets checked to make sure they input something.
As for goto, you just make a label in the code and then goto tells it to return to the label. This can be used for more than just looping; however, you should not be in need of it unless you have some tangled, complex web of a set of loops, which is rarely the case.