KonsolScript:Tutorials:Looping

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

Looping

Often times, there's a need to repeat a series of commands. This can be done with looping.

KonsolScript, supports two types of looping.

While statement

The while statement executes a series of commands written inside its scope.

//syntax of while
  while(/* conditional*/) {
    //scope...
  }

The syntax is as simple as what's shown above. All you have to do is fill-up the blanks. :D

Let's say we want to repeatedly output "Hello!", we write Konsol:Log inside scope of while.

//demonstrating while statement
  while(/* conditional*/) {
    //scope...
    Konsol:Log("Hello!")
  }

But the scope will only be executed when the conditional question answers yes. So, we need a conditional that leads to answer yes -- let's add 1 EQ 1.

//demonstrating while statement (part 2)
  while(1 EQ 1) {
    //scope...
    Konsol:Log("Hello!")
  }

There you go. A while statement.

For statement

A for statement works just like while does. But for statement differ in syntax since a for loop counts how many times it has loop.

//syntax of for statement
  for(init;/*conditional*/;next) {
    //scope...
  }

Looks more complicated, huh? Here's a simple demo.

//demonstrating for statement
function main() {
  Var:Number x;
  for(x=1; x LE 10; x++) {
    //scope...
    Konsol:Log("Hello!")
  }
}

The sample above prints out "Hello!", 10 times.

Var:Number x;

First, we need to declare a variable to be used for counting.

x=1;

Then we have the init (from the word initialize). Here, we begin our counting.

x LE 10;

Then we need to provide the maximum number to count. We typed-in LE 10 since we only wanted to count from 1 to 10.

x++

Then we have our counting method. x++ means we add 1 to x every loop.

for(x=1; x LE 10; x++) {
    //scope...
  }

As a single-line command, what our code meant is to execute the commands in its scope while counting from 1 to 10. Once 10 is reached, execute for the last time the command/s in scope of for statement.

Konsol:Log("Hello!")

It so happen we only wanted to print "Hello!".

So there you have a for statement.

Last Words

We can actually count from 10 to 1. We just have to change the logic of the program.

//demonstrating for statement counting downward
function main() {
  Var:Number x;
  for(x=10; x GE 1; x--) {
    //scope...
    Konsol:Log("Hello!")
  }
}

We can also do counting on while statement.

//demonstrates counting with while statement
function main() {
  Var:Number x;
  x=1;
  while(x LE 10) {
    //scope...
    Konsol:Log("Hello!")
    x++;
  }
}

And of course, it could do some countdown too. Choose whatever looks more elegant to you.

~creek23~