Thread: Looping
View Single Post
  #15  
Old 12-16-2001, 01:40 AM
kyle0654 kyle0654 is offline
-. .`
kyle0654's Avatar
Join Date: Mar 2001
Posts: 1,000
kyle0654 will become famous soon enough
oye...why must idiots insult people who can't script as well as them and haven't done anything to deserve harsh words?

anyway...


timeout loops
NPC Code:

if (playerenters||timeout) {
hide;
sleep 2;
show;
sleep 2;
timeout = .05;
}



Timeout will make the timeout counter count down to 0 if you set it to anything above 0, and when it gets to 0, it will trigger a flag called timeout on the npc. If you place a timeout at the end of an if (timeout) statement, then it will loop.


while loops
NPC Code:

if (playerenters) {
while (1==1) {
hide;
sleep 2;
show;
sleep 2;
}
}



While is just like if, except when it finds a } it will go back to the while () and check the statement again. If the conditions in the brackets are still true, it will do the loop again. Otherwise, it will jump back to the } and continue with the script.

Above, I have while (1==1), which will create an infinite loop.


for loops
NPC Code:

if (playerenters) {
for (i = 0; i>=0; i++) {
hide;
sleep 2;
show;
sleep 2;
}
}



For is very useful, and most loops you encounter (that aren't timeout loops) will use for. If you have read the commands.rtf, you should notice that the syntax for for is something like:

for (initial; condition; increment) {

Now, the loop above could be written like this, and work the same way:
NPC Code:

if (playerenters) {
i = 0;
while (i>=0) {
hide;
sleep 2;
show;
sleep 2;
i++;
}
}


And, if you look at the debugger while playing (F6), you'll notice that your for loops are changed into while loops when they're processed by the scripting engine. The reason you use for though is because it's much easier to write, and is harder to mess up with.

The best advantage with for loops is that you can use the variable that is looping in your scripting. So, you could loop through an entire array and add all the numbers like this:
NPC Code:

if (playerenters) {
sum = 0;
myarray = {0,13,16,64,34};

for (i = 0; i < arraylen(myarray); i++) {
sum += myarray[i];
}

message #v(sum);
}


Now, I'll assume you don't know arrays since you're asking about loops, but just remember that loops can be very useful with arrays when you get to them.
Reply With Quote