Team LiB
Previous Section Next Section

1.9. Loops

Loops are used to iterate through a particular set of statements based upon a set of conditions. The following sections discuss the different types of loop statements supported by NASL.

1.9.1. for

A for loop expects three statements separated by semicolons as arguments. The first statement is executed first, and only once. It is most frequently used to assign a value to a variable, which is usually used by the loop to perform iteration. The second statement is a condition that should return true for the loop to continue looping. The third statement is invoked by the for loop after every iteration, and is used to increment or decrement the iteration variable. For example, the following for loop prints all the values of the array myports:

for(i=0; i < max_index(myports); i++)
{
    display(myports[i],"\n");
}

The function max_index() returns the number of elements in an array, and we use it in our for loop to ensure that the value of i is within range.

1.9.2. foreach

You can use the foreach statement to loop for every array element. This is useful in cases when you need to iterate through an array. For example, the following loop iterates through myports[] and prints the values contained in it:

foreach i (myports)
{
    display (i, "\n");
}

1.9.3. repeat...until

The condition specified after until is evaluated after the loop is executed. This means a repeat...until loop always executes at least once. For example, the following displays the string Looping!:

i=0;

repeat
{
    display ("Looping!\n");

} until (i == 0);

1.9.4. while

A while loop expects one conditional statement and loops as long as the condition is true. For example, consider the following while loop, which prints integers 1 to 10:

i=1;

while(i <= 10)
{
    display(i, "\n");
    i++;
}

    Team LiB
    Previous Section Next Section