# Variables

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.

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 not possible for `static` variables. Without initialization variables always start with `nil`.
Additional variable declarations may follow, separated by comma. The declaration must always be ended with a semicolon.
Example:
static object_count; local time_to_live = 100;

protected func Initialize() { object_count++; }

protected func Destruction() { object_count--; }

protected func Timer() { if(!--time_to_live) { RemoveObject(); return; }

var obj = FindObject(Find_ID(Clonk), Sort_Distance());

if(ObjectDistance(obj) < 20) DoDamage(-10, obj);

return
; }
Addendum:

- Object local variable declarations are also valid in #appendto or #include script extensions.
- When `this` is a definition, local variables are constant. That protects against accidental modifications that would appear to work fine while there is only one object of a kind, but break in subtle ways as soon as there are multiple instances.
- Using the `obj.foo` or `obj["foo"]` notation one can 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 multiple times, the variable will still 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
her-long ago
Günther
2010