Named Variables
Variables are placeholders for values stored in a script. A variable stores a value in one of several
data types.
There are three different scopes in which a variable can be declared. Variables are not visible outside their declared scope.
Keyword |
Scope |
Location |
var |
function local |
Function |
local |
object local |
Object Script |
static |
global |
any script |
Variables are declared using the following syntax:
{ var / local / static } name [= expr] [, name [= expr] ... ];
The variable's scope, followed by the variable's name.
Optionally, you can assign a value to the variable directly at declaration time. However, this is possible for function local (var
) variables only. Without initialization variables always start with value 0.
Additional variable declarations may follow, separated by comma. The declaration must always be ended with a semicolon.
Example:
static iObjectCount;
local iTimeToLive;
protected func Initialize()
{
iObjectCount++;
iTimeToLive = 100;
}
protected func Destruction()
{
iObjectCount--;
}
protected func Timer()
{
if(!--iTimeToLive)
{
RemoveObject();
return();
}
var obj = FindObject(CLNK, 0, 0, -1, -1);
if(ObjectDistance(obj) < 20)
DoDamage(-10, obj);
return();
}
Addendum:
- Object local variable declarations are also valid in #appendto or #include script extensions.
- Using the functions VarN(), LocalN(), and GlobalN() you can access variables indirectly. Using LocalN() you can specifically access local variables in other objects.
- If two variables of the same name but differing scope are valid at the same time, then the variable of the smaller scope will be used, meaning for example an object local variable will "cover up" a global variable within its own scope.
- If the same variable is declared multiply, then still the variable will exist only once and no error is thrown. Multiple initializations are considered regular assignments and executed in order, respectively.
- A
static
variable may also be used in object scripts (see example). If a static
variable of the same name is defined in another script, the name will refer to the same variable.
PeterW, ewig her