Team LiB
Previous Section Next Section

1.10. Functions

A function is a block of code that performs a particular computation. Functions can be passed input parameters and return a single value. Functions can use arrays to return multiple values.

The following function expects the integer value port as input. The function returns 1 if port is even, 0 if it is odd:

function is_even (port)
{
    return (!(port%2));
}

The function is_even( ) performs the modulo operation to obtain the remainder when port is divided by 2. If the modulo operation returns 0, the value of port must be even. If the modulo operation returns 1, the value of port must be odd. The ! operator is used to invert the evaluation, and this causes the function to return 1 when the modulo operation evaluates to 0, and 0 when the modulo operation evaluates to 1.

Functions in NASL do not care about the order of parameters. To pass a parameter to a function, precede it with the parameter namefor example, is_even(port:22). Here is an example of how you can invoke is_even( ):

for(i=1;i<=5;i++)
{
    display (i," is ");

    if(is_even(port:i))
        display ("even!");
    else
        display ("odd!");

    display ("\n");
}

When executed, the preceding program displays the following:

1 is odd!
2 is even!
3 is odd!
4 is even!
5 is odd!

The NASL library consists of some functions that are not global. Such functions are defined in .inc files and you can include them by invoking the include() function call. For example:

include("http_func.inc");
include("http_keepalive.inc");

    Team LiB
    Previous Section Next Section