Function Declarations

From NWN Lexicon
Jump to: navigation, search

Functions can be declared (or defined) which can then be invoked (called) from anywhere within the script you defined it in. This has many important uses:

  • Grouping similar code blocks for ease of readability.
  • Cutting down on redundancy when the same statements are to be called repeated from different places in a script.
  • Saving useful routines in an include file.
/* prototype
type functionName(type parameter1, ..., type parameterN)
{
    // code block ...
    return value;
}
*/
  • type is the data type that the function will return. Functions that don't return values should be declared as type void (although you can still use the return statement in them to exit the function).
  • functionName should be alphanumeric names with the first character being a letter or underscore. Underscores are permitted, but not recommend (underscores should be limited to identifier names and constant expressions).
  • The parameters are optional but must be declared with a valid data type, and have unique, well-formed names (alphanumeric, starting with a letter or underscore). These parameters are only available within the scope of the function body, and are not available to code outside the function's execution (scope). Changes to the parameter's value within the function body do not affect the value of the actual variable passed in as the parameter (if a literal expression).
  • code block are the statements to actually be executed by the function.
  • return is used to return the value specified after the return statement to the calling function (return can be called with no value to just return the flow of the execution to the calling function).
string CombineStrings(string str1, string str2) 
{
    return str1 + str2;
}

Furthermore, you can provide default values for some parameters, namely those of types float, int, string, and object (only OBJECT_INVALID and OBJECT_SELF work for object). A default value means that, when the function is called, if no value is provided for that parameter, the function will use the default one. These optional parameters must be listed AFTER the non-optional ones. Also, variables can't be used as default values, only true integers, floats, strings, and constants.

//This works fine:
void MyFunction(float fSomething, int nSomething = 0, object oSomething = OBJECT_SELF)
{
 
}
 
//This doesn't work:
int nDefault = 0;
 
void MyFunction(float fSomething, int nSomething = nDefault, object oSomething = OBJECT_SELF)
{
 
}
 
//But this does:
const int nDefault = 0;
 
void MyFunction(float fSomething, int nSomething = nDefault, object oSomething = OBJECT_SELF)
{
 
}

 author: Ryan Hunt, editor: Lilac Soul, additional contributor(s): Lilac Soul