Wednesday, August 27, 2008

Loopity Loops (or Round and Round We go)

Ok, sometimes actions will need to be repeated a certain number of times or if certain conditions exist. Torque gives us the While loop and the For loop to deal with times like these.

NOTE: do NOT capitalize while and for in your code. Just don't. Trust me.

The While loop is used if we want something to occur while a specific condition exists (hence the 'While' loop). Here is the syntax for a While loop:

while (condition)
{
Commands
}

Your never want to get stuck in a loop. If you do, your program will basically stop responding. You should always ensure that a combination of the condition and the commands gives the program a way to get out of the loop.

Same While Loop:

//wailingWhile.cs
//
function oucheffect ()
{
%playerHP = 1; //gives initial player health
$upHPs = 0; //Initialize %upHPs
while (%playerHP <30) //set the condition for the loop
{
echo ("OMG it still hurts!"); //it is called WAILINGwhile afterall
$upHPs = GetRandom(30); //assigns a random number between 0 and 30 to %healPts
%playerHP = %playerHP + $upHPs;//increase %playerHP
echo ("Player healed for "@$upHPts@". Player health now "@%playerHP@".");//gives us some output to see if the function is working
}
}

Go ahead and try that in the Torque console to see what happens.

The next type of loop is the For loop. Basically this is for when you want an action to occur a specific number of times.

For Loop syntax:

for (initial value; state check; update value)
{
commands
}

Here is a simple module using a for loop to print a specific amount of random numbers:

//rndfor.cs
//
function countem ()
{
for (%counter = 1; %counter <= 10; %counter++)
{
Echo(GetRandom(10));
}
}

Give that one a try as well. Always remember: when coding, for and while are not capitalized. It will generate a parser error that will have you looking for the mistake for hours. If you don't know 100% that it should be uppercase, use lower. In my experience so far it is safer.

No comments: