jeffheaton's picture

    A function is a named block of code that can be called from elsewhere in the script. First we will examine a simple function that accepts no parameters and does not return anything. The following code demonstrates this.

Listing 2.3: Simple Function

integer count;

display()
{
    llSay(0, "Count: " + (string)count); 
}

default
{
    state_entry()
    {
        count = 0;
    }
    
    touch_start(integer total_number)
    {
        count ++;
        display();
    }
}

    The above code defines a function named display. Notice where the function is declared. It is declared outside of any state. Functions cannot be defined inside of a state. Only events can be defined inside of a state. Events will be covered in the next section.

    The above function simply displays the count. The new function is called by the following line of code.

display();

    Functions can also accept parameters. The following script demonstrates a function that accepts one parameter.

Listing 2.4: Functions with Parameters

integer count;

display(integer i)
{
    llSay(0, "Count: " + (string)i); 
}

default
{
    state_entry()
    {
        count = 0;
    }
    
    touch_start(integer total_number)
    {
        count ++;
        display(count);
    }
}

    The display function accepts a single parameter named i. This parameter is the value that is to be displayed. To call a function with a parameter the following code is used.

display(count);

    As can be seen, the count variable is passed into the display function. It is not possible for a function to modify the variable that was passed to it.

    Functions can also return values. The following script demonstrates how to use a function that accepts two parameters and returns a value.

Listing 2.5: Function that Returns Values

integer count;

integer multiply(integer x,integer y)
{
    integer result = x * y;
    return result; 
}

default
{
    state_entry()
    {
        count = 0;
    }
    
    touch_start(integer total_number)
    {
        integer x = multiply(5,10);
        llSay(0, "Result: " + (string)x);
    }
}

    The above script declares the multiply function to return an integer. Did you notice the keyword integer before the “multiply” function name? This specifies the type that the function should return. Once a type is specified, the function must contain a return statement. The return statement specifies what value should be returned to the caller of the function. The following line of code calls the multiply function.

integer x = multiply(5,10);

    The parameters 5 and 10 are passed into the function. The multiply function then multiplies these two numbers and returns the result. The asterisk (*) operator is used to multiply. The slash (/) operator is used to divide.


Copyright 2005 - 2012 by Heaton Research, Inc.. Heaton Research™ and Encog™ are trademarks of Heaton Research. Click here for copyright, license and trademark information.