Defining functions in script



When you run a script, the default behavior is to place the entire contents of the script inside a function so that the Angelscript engine has an entry point to call into. For example, suppose we have the simple script below in our script panel.

The full script given to the Angelscript engine in this case would be:
void main() {
    print( "hello" );
}
... and the function 'main' would be called to execute the script. This is done to make the most common and simple scripts easier to set up, but it prevents you from defining and use your own functions.

For example, suppose you wanted to have a function to return the length of the hypotenuse of a right-angled triangle, given the lengths of the other two sides. You might attempt to do that like below, but as we can see it fails to compile...

..because the full script given to the Angelscript engine is grammatically incorrect:
void main() {
    float hypotenuse(float a, float b) {
        return sqrt( a*a + b*b );
    }

    print( "Answer:" + hypotenuse(3,4) );
}

To avoid this default behavior and define your own functions to use, you need to give an entry point function of the form "void main()".

If the function "void main()" is detected in the script, the enclosing 'main' will not be placed around the script contents, and the 'main' function will be used as the entry point.

Caution: The main function is detected by using regular expressions that do not take into account whether the function is inside a commented-out region. If you want to comment out the part of the script that includes the main function, you will also need to alter the main function (eg. add or remove some text so that the function signature no longer matches "void main()"). Hopefully this behavior can be improved in future.