Variables: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
(Informative box for local variable deallocation)
(Page refresh)
Line 1: Line 1:
{{SideTOC}}
{{SideTOC}}


A '''variable''' is a "storage container" or "named placeholder" for data. You can read and modify the data once this container is created.
A '''variable''' is a "storage container" or "named placeholder" for data. You can read and modify the data once this container is created.<br>
Its "name" is referenced as [[Identifier]].




Line 14: Line 15:
== Initialization ==
== Initialization ==


The first thing to do to create a variable is to find its name, also called [[Identifier|identifier]]; this name must be speaking to the reader.
The first thing to do to create a variable is to find its name, also called [[Identifier|identifier]]; this name must be speaking to the reader - keep in mind that code is meant to be read by ''human beings'' (see [[Code Best Practices#Variable format|Code Best Practices - Variable format]]).
Once you find a proper name, you have to tell the game engine that you are going to use this identifier. This is called '''initialization''' or '''declaration'''. This is how it is done:
 
Once a proper name is found, it can be used to '''declare''' (or '''initialise''') the variable:


  myVariable = 0;
  myVariable = 0;


Before [[{{arma2}}]], querying undefined (or uninitialized) variables returns [[nil]] (undefined value); from [[{{arma2}}]] and later, it returns an "Error Undefined variable in expression" error.
Before [[{{arma2}}]], querying undefined (or uninitialised) variables returns [[nil]] (undefined value); from [[{{arma2}}]] and later, it returns an "Error Undefined variable in expression" error.
{{Informative | An undefined ([[nil]]) variable converted to [[String]] with [[str]] will return [[scalar bool array string 0xe0ffffef]] (in [[Armed Assault]]) and [[scalar bool array string 0xfcffffef]] (in [[Operation Flashpoint]]).<br>Unless trying to emulate [[isNil]], '''always''' declare your variable before trying to access it.}}
{{Informative | An undefined ([[nil]]) variable converted to [[String]] with [[format]] or [[str]] will return [[scalar bool array string 0xe0ffffef]] (in [[Armed Assault]]) and [[scalar bool array string 0xfcffffef]] (in [[Operation Flashpoint]]).<br>
Unless trying to emulate [[isNil]], '''always''' declare your variable before trying to access it.}}




== Deletion ==
== Deletion ==


Once created, variables will take up space in the computer's memory. This is not drastic for small variables, but if a big number of very large variables is used, some unneeded ones should be undefined in order to free up memory. This can be done by setting their value to [[nil]].
Once created, variables take up space in the computer's memory.<br>
This is not drastic for small variables, but if a big number of very large variables is used, it is recommended to undefine the unneeded ones in order to free up memory. This can be done by setting their value to [[nil]].


  hugeVariable = nil;
  HugeVariable = [[nil]];


This effectively destroys a variable as if it had never existed.
This effectively destroys a variable as if it had never existed.


{{Informative | Local variables are automatically freed (deleted from memory) when their scope is exited, avoiding the need to manually deallocate them.}}
{{Informative | Local variables are automatically freed (deleted from memory) when their scope is exited, avoiding the need to manually deallocate them.}}


== Scopes ==
== Scopes ==
Line 37: Line 42:
Variables are only visible in certain scopes of the game. This prevents name conflicts between different variables in different [[Script (File)|scripts]].
Variables are only visible in certain scopes of the game. This prevents name conflicts between different variables in different [[Script (File)|scripts]].


There are three scopes:
There are two main scopes:


; local
=== Global Scope ===
: A variable is only visible in the [[Script (File)|script]], or [[function]], or [[Control Structures]] in which it was defined.


; global
A global variable is visible from all scripts on the computer on which it was defined.
: A variable is visible on the whole computer where it was defined.
Names given to units in the [[Mission Editor]] are also global variables pointing to those units, which may not be redefined or modified.
<!-- TODO: mention missionNamespace? -->
{{Important | a global variable can be different from one machine to another!<!--
--> To ensure the global variable's proper broadcast, see [[publicVariable]], [[publicVariableServer]] and [[publicVariableClient]].
If the value changes, the broadcast must be reapplied. e.g:
<code>GlobalVariable {{=}} 33;<br><!--
-->[[publicVariable]] "GlobalVariable";<br><br><!--
-->GlobalVariable {{=}} 42;<br><!--
-->[[publicVariable]] "GlobalVariable"; {{cc|updates the value for everyone}}</code>
}}


; public
=== Local Scope ===
: A global variable is broadcasted over the network and visible on all computers connected to the network.


=== Local Variables ===
A local variable is only visible in the [[Script (File)|script]], [[function]] or [[Control Structures|Control Structure]] in which it was defined.


Local variables are only visible in a specific [[Script (File)|script]], or [[function]], or [[Control Structures]].
{{Informative | A local variable cannot be broadcast. In order to broadcast a local variable's ''value'', it must be assigned to a global variable first:
<code>[[private]] _myLocalVariable {{=}} 33;<br><!--
-->[[publicVariable]] "_myLocalVariable"; {{cc|incorrect}}<br><br><!--
-->GlobalVariable {{=}} _myLocalVariable;<br><!--
-->[[publicVariable]] "GlobalVariable"; {{cc|correct}}</code>}}


The [[Identifier|identifier]] of local variables in a [[Script (File)|script]] always has to started with an underscore.
=== Local Variables Scope ===


_myLocalVariable = 0;
Local variables in [[call]]able code (e.g [[Arma 3 Functions Library|Functions]]) should be scoped using the command [[private]],
 
otherwise you may modify local variables of the [[call]]ing script that are visible in the function.
In [[Arma 3 Functions Library|functions]] you should additionally mark variables as private using the command [[private]]. Otherwise, you may modify local variables of the [[call]]ing script that are visible in the function.


  {{cc|Since {{arma3}} v1.54}}
  {{cc|Since {{arma3}} v1.54}}
  [[private]] _myLocalVariable = 0;
  [[private]] _myLocalVariable = 0;
   
   
  {{cc|Before {{arma3}} v1.54}}
  {{cc|From {{arma2}} until {{arma3}} v1.54}}
[[local]] _myLocalVariable = 0;
{{cc|Before {{arma2}}}}
  [[private]] "_myLocalVariable";
  [[private]] "_myLocalVariable";
  _myLocalVariable = 0;
  _myLocalVariable = 0;
   
   
  {{cc|Alternative method to private multiple local variables at the same time}}
  {{cc|Alternative method to private multiple local variables at the same time}}
  [[private]] ["_myLocalVariable1", "_myLocalVariable2", (...)];
  [[private]] ["_myLocalVariable1", "_myLocalVariable2"];
  _myLocalVariable1 = 1;
  _myLocalVariable1 = 1;
  _myLocalVariable2 = 2;
  _myLocalVariable2 = 2;
(...)


If a [[private]] variable is initialised within a [[Control Structures|Control Structure]] (i.e. [[if]], [[for]], [[switch]], [[while]]),
its existence will be limited to it and its sub-structures - the variable does not exist outside of the structure and will be seen as undefined.


=== Global Variables ===


Global variables are visible on the whole computer where they are defined. Names given to units in the [[Mission Editor]] are also global variables pointing to those units, which may not be redefined or modified.
<!--
don't judge me
-->
<table style="font-family: monospace; font-size: 1.1em; line-height: 1.15em; margin: auto; tab-size: 4; -moz-tab-size: 4; white-space: pre">
<tr>
<th colspan="5">Variables<br>lifespan</th>
<th style="font-size: 1.25em">Code</th>
</tr>
<tr>
<td rowspan="18" style="background-color: orange; border-radius: 10em"></td>
<td></td>
<td></td>
<td></td>
<td rowspan="18"></td>
<td>'''{{Color|darkorange|TAG_GlobalVariable}}''' = "Global variable"; {{cc|Global variable is accessible from any scope}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><wbr /></td>
</tr>
<tr>
<td rowspan="16" style="background-color: darkgreen; border-radius: 10em"></td>
<td><wbr /></td>
<td><wbr /></td>
<td>[[private]] '''{{Color|darkgreen|_myVariable}}''' = 0;</td>
</tr>
<tr>
<td></td>
<td></td>
<td>[[if]] ('''{{Color|grey|_condition}}''') [[then]]</td>
</tr>
<tr>
<td></td>
<td></td>
<td>{</td>
</tr>
<tr>
<td></td>
<td></td>
<td> '''{{Color|darkgreen|_myVariable}}''' = 1;</td>
</tr>
<tr>
<td rowspan="2" style="background-color: blue; border-radius: 10em"></td>
<td></td>
<td> [[private]] '''{{Color|blue|_myVariable}}''' = 2;</td>
</tr>
<tr>
<td></td>
<td> '''{{Color|blue|_myVariable}}''' = 3;</td>
</tr>
<tr>
<td></td>
<td></td>
<td>} [[else]] {</td>
</tr>
<tr>
<td></td>
<td></td>
<td> '''{{Color|darkgreen|_myVariable}}''' = 4;</td>
</tr>
<tr>
<td></td>
<td rowspan="1" style="background-color: purple; border-radius: 10em"></td>
<td> [[private]] '''{{Color|purple|_anotherVariable}}''' = 10;</td>
</tr>
<tr>
<td></td>
<td></td>
<td>};</td>
</tr>
<tr>
<td></td>
<td></td>
<td><wbr /></td>
</tr>
<tr>
<td></td>
<td></td>
<td>[[hint]] [[str]] _myVariable; {{cc|if '''{{Color|grey|_condition}}''' is [[true]],  _myVariable's value is '''{{Color|darkgreen|1}}''';}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td> {{cc|if '''{{Color|grey|_condition}}''' is [[false]], _myVariable's value is '''{{Color|darkgreen|4}}'''.}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td><wbr /></td>
</tr>
<tr>
<td></td>
<td></td>
<td>{{cc|trying to use '''{{Color|purple|_anotherVariable}}''' here would result in an [[Debugging Techniques#Common errors|"undefined variable" error]],}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td>{{cc|'''{{Color|purple|_anotherVariable}}''' being only scoped in the [[else]].}}</td>
</tr>
</table>


[[Identifier]]s of global variables ''must not'' start with underscore. Besides this, they use the same rules as for all [[Identifier|identifiers]].
<!-- Original code -->
 
<!--
myGlobalVariable = 0;
[[if]] ('''{{Color|grey|_condition}}''') [[then]]
 
=== Public Variables ===
 
Public variables are global variables, visible on several computers in the network. You can never have true public variables, but you can emulate their behaviour.
 
The value of a global variable gets broadcasted over the network using [[publicVariable]]. After the call of this command the variable will have the same value on all [[Client|clients]]. Once you modify the variable though you have to broadcast it manually ''again'' with [[publicVariable]].
 
 
== More information relative to private variable ==
 
If a private variable is initialized within a [[Control Structures]] (i.e. [[if]], [[for]], [[switch]], [[while]]) its scope will stay ''within'' this structure (i.e. outside of the structure it will still be seen as undefined).
 
<code>[[if]] ([[alive]] [[player]]) [[then]]
{
{
[[private]] _living = true;
'''{{Color|darkgreen|_myVariable}}''' = 1;
[[private]] '''{{Color|blue|_myVariable}}''' = 2;
'''{{Color|blue|_myVariable}}''' = 3;
} [[else]] {
'''{{Color|darkgreen|_myVariable}}''' = 4;
[[private]] '''{{Color|purple|_anotherVariable}}''' = 10;
};
};
[[hint]] [[format]] ["%1", _living];</code>
Returns an error, since the private variable was not initialized ''before'' being used within a control structure.


<code>[[private]] _living = false;
[[hint]] [[str]] _myVariable; {{cc|if '''{{Color|grey|_condition}}''' is [[true]],  _myVariable's value is '''{{Color|darkgreen|1}}'''}}
[[if]] ([[alive]] [[player]]) [[then]]
{{cc|if '''{{Color|grey|_condition}}''' is [[false]], _myVariable's value is '''{{Color|darkgreen|4}}'''.}}
{
<wbr />
_living = true;
{{cc|trying to use '''{{Color|purple|_anotherVariable}}''' here would result in an [[Debugging Techniques#Common errors|"undefined variable" error]],}}
};
{{cc|'''{{Color|purple|_anotherVariable}}''' being only scoped in the [[else]].}}
[[hint]] [[format]] ["%1", _living];</code>
-->
Returns [[true]] since the variable was initialized before the [[if]]..[[then]] statement.<br>
To initialize private variables so that they are available throughout the whole script (including any control structures), initialize it via the [[private]] command (e.g. {{Inline code | [[private]] _varname;}}) at the beginning of the script.


{| style="margin: auto"
! style="width: 50%" | Incorrect
! style="width: 50%" | Correct
|-
| <code><br>[[if]] ([[alive]] [[player]]) [[then]]<br><!--
-->{<br><!--
--> [[private]] _living = [[true]];<br><!--
-->};<br><!--
-->{{cc|throws an error since the private variable was}}<br><!--
-->{{cc|not initialised outside the [[if]] control structure.}}<br><!--
-->[[hint]] [[format]] ["%1", _living];</code>
|<code>[[private]] _living = [[false]];<br><!--
-->[[if]] ([[alive]] [[player]]) [[then]]<br><!--
-->{<br><!--
--> _living = [[true]];<br><!--
-->};<br><br><br><!--
-->[[hint]] [[format]] ["%1", _living]; {{cc|returns [[true]]}}</code>
|}


== Data Types ==
== Data Types ==


Variables may store certain values. The kind of the value specifies the ''type'' of the variable. Different [[Operators|operators]] and [[:Category:Scripting Commands|commands]] require variables to be of different types.
Variables may store values of a certain [[Data Types|Data Type]] ([[String]], [[Number]], etc). The kind of the value specifies the ''type'' of the variable.
Different [[Operators|operators]] and [[:Category:Scripting Commands|commands]] require variables to be of different types.


Read the article [[Data Types]] for more information about variable types.
A variable is not strongly typed and changes its type according to the new data:
[[private]] "_myVariable"; {{cc|[[nil]]}}
_myVariable = '''{{Color|darkorange|1}}'''; {{cc|1 ([[Number]])}}
_myVariable = {{Color|red|"test"}}; {{cc|"test" ([[String]])}}




== Multiplayer Considerations ==
== Multiplayer Considerations ==


Storing functions ( or any callable code) into global variables without securing them with [[compileFinal]] (since {{arma3}}) is a '''very''' bad practice in multiplayer. The biggest security risk would be to see it being overriden by a malicious usage of [[publicVariable]], setting potentially dangerous code in it.
Storing functions (or any callable code) into global variables without securing them with [[compileFinal]] (since {{arma3}}) is a '''very''' bad practice in multiplayer.
The biggest security risk would be to see it being overridden by a malicious usage of [[publicVariable]], setting potentially dangerous code in it.


The best option is to declare your function in [[Arma 3 Functions Library|CfgFunctions]] so the engine secures it for you.
The best option is to declare your function in [[Arma 3 Functions Library|CfgFunctions]] so the engine secures it for you.


If you want to manually create a global function, the best practice is the following:
If you want to manually create a global function anyway, the best practice is the following:
  myGlobalVarFunction = [[compileFinal]] [[preprocessFileLineNumbers]] "functions\directory\functionsFile.sqf";
  TAG_MyGlobalVariableFunction = [[compileFinal]] [[preprocessFileLineNumbers]] "functionFile.sqf";
 
{{Important | You must execute said code '''on every machine''' that will need the function, and '''not''' [[publicVariable]] its content!}}




Line 130: Line 264:
* [[Identifier]]
* [[Identifier]]
* [[Data Types]]
* [[Data Types]]
* [[Control Structures]]
* [[Magic Variables]]
* [[Magic Variables]]
* [[private]] ({{arma3}})
* [[private]] ({{arma3}})

Revision as of 16:26, 14 May 2020

Template:SideTOC

A variable is a "storage container" or "named placeholder" for data. You can read and modify the data once this container is created.
Its "name" is referenced as Identifier.


Requirements

The following links guide to the basics to understand this article:


Initialization

The first thing to do to create a variable is to find its name, also called identifier; this name must be speaking to the reader - keep in mind that code is meant to be read by human beings (see Code Best Practices - Variable format).

Once a proper name is found, it can be used to declare (or initialise) the variable:

myVariable = 0;

Before Arma 2, querying undefined (or uninitialised) variables returns nil (undefined value); from Arma 2 and later, it returns an "Error Undefined variable in expression" error.

An undefined (nil) variable converted to String with format or str will return scalar bool array string 0xe0ffffef (in Armed Assault) and scalar bool array string 0xfcffffef (in Operation Flashpoint).
Unless trying to emulate isNil, always declare your variable before trying to access it.


Deletion

Once created, variables take up space in the computer's memory.
This is not drastic for small variables, but if a big number of very large variables is used, it is recommended to undefine the unneeded ones in order to free up memory. This can be done by setting their value to nil.

HugeVariable = nil;

This effectively destroys a variable as if it had never existed.

Local variables are automatically freed (deleted from memory) when their scope is exited, avoiding the need to manually deallocate them.


Scopes

Variables are only visible in certain scopes of the game. This prevents name conflicts between different variables in different scripts.

There are two main scopes:

Global Scope

A global variable is visible from all scripts on the computer on which it was defined. Names given to units in the Mission Editor are also global variables pointing to those units, which may not be redefined or modified.

a global variable can be different from one machine to another! To ensure the global variable's proper broadcast, see publicVariable, publicVariableServer and publicVariableClient.

If the value changes, the broadcast must be reapplied. e.g:

GlobalVariable = 33;
publicVariable "GlobalVariable";

GlobalVariable = 42;
publicVariable "GlobalVariable"; // updates the value for everyone

Local Scope

A local variable is only visible in the script, function or Control Structure in which it was defined.

A local variable cannot be broadcast. In order to broadcast a local variable's value, it must be assigned to a global variable first: private _myLocalVariable = 33;
publicVariable "_myLocalVariable"; // incorrect

GlobalVariable = _myLocalVariable;
publicVariable "GlobalVariable"; // correct

Local Variables Scope

Local variables in callable code (e.g Functions) should be scoped using the command private, otherwise you may modify local variables of the calling script that are visible in the function.

// Since Arma 3 v1.54
private _myLocalVariable = 0;

// From Arma 2 until Arma 3 v1.54
local _myLocalVariable = 0;

// Before Arma 2
private "_myLocalVariable";
_myLocalVariable = 0;

// Alternative method to private multiple local variables at the same time
private ["_myLocalVariable1", "_myLocalVariable2"];
_myLocalVariable1 = 1;
_myLocalVariable2 = 2;

If a private variable is initialised within a Control Structure (i.e. if, for, switch, while), its existence will be limited to it and its sub-structures - the variable does not exist outside of the structure and will be seen as undefined.


Variables
lifespan
Code
TAG_GlobalVariable = "Global variable"; // Global variable is accessible from any scope
private _myVariable = 0;
if (_condition) then
{
_myVariable = 1;
private _myVariable = 2;
_myVariable = 3;
} else {
_myVariable = 4;
private _anotherVariable = 10;
};
hint str _myVariable; // if _condition is true, _myVariable's value is 1;
// if _condition is false, _myVariable's value is 4.
// trying to use _anotherVariable here would result in an "undefined variable" error,
// _anotherVariable being only scoped in the else.


Incorrect Correct

if (alive player) then
{
private _living = true;
};
// throws an error since the private variable was
// not initialised outside the if control structure.
hint format ["%1", _living];
private _living = false;
if (alive player) then
{
_living = true;
};


hint format ["%1", _living]; // returns true


Data Types

Variables may store values of a certain Data Type (String, Number, etc). The kind of the value specifies the type of the variable. Different operators and commands require variables to be of different types.

A variable is not strongly typed and changes its type according to the new data:

private "_myVariable";	// nil
_myVariable = 1;		// 1 (Number)
_myVariable = "test";	// "test" (String)


Multiplayer Considerations

Storing functions (or any callable code) into global variables without securing them with compileFinal (since Arma 3) is a very bad practice in multiplayer. The biggest security risk would be to see it being overridden by a malicious usage of publicVariable, setting potentially dangerous code in it.

The best option is to declare your function in CfgFunctions so the engine secures it for you.

If you want to manually create a global function anyway, the best practice is the following:

TAG_MyGlobalVariableFunction = compileFinal preprocessFileLineNumbers "functionFile.sqf";
You must execute said code on every machine that will need the function, and not publicVariable its content!


See also