Variables: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
m (Text replacement - "[[Script (File)|" to "[[Script File|")
m (Some wiki formatting)
Line 18: Line 18:
Once a proper name is found, it can be used to '''declare''' (or '''initialise''') the variable:
Once a proper name is found, it can be used to '''declare''' (or '''initialise''') the variable:


myVariable = 0;
<sqf>myVariable = 0;</sqf>


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




Line 31: Line 33:


Variable deletion is done by setting its value to [[nil]]:
Variable deletion is done by setting its value to [[nil]]:
HugeVariable = [[nil]];
<sqf>HugeVariable = nil;</sqf>


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




Line 50: Line 52:
--> To ensure the global variable's proper broadcast, see [[publicVariable]], [[publicVariableServer]] and [[publicVariableClient]].
--> To ensure the global variable's proper broadcast, see [[publicVariable]], [[publicVariableServer]] and [[publicVariableClient]].
If the value changes, the broadcast must be reapplied. e.g:
If the value changes, the broadcast must be reapplied. e.g:
<code>GlobalVariable {{=}} 33;<br><!--
<sqf>
-->[[publicVariable]] "GlobalVariable";<br><br><!--
GlobalVariable = 33;
-->GlobalVariable {{=}} 42; {{cc|GlobalVariable is now 42 '''on the current machine''' but still 33 on the others}}<br><!--
publicVariable "GlobalVariable";
-->[[publicVariable]] "GlobalVariable"; {{cc|updates the value to 42 for everyone}}</code>
 
GlobalVariable = 42; // GlobalVariable is now 42 on the current machine but still 33 on the others
publicVariable "GlobalVariable"; // updates the value to 42 for everyone
</sqf>
}}
}}


Line 61: Line 66:


{{Feature | 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:
{{Feature | 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><!--
<sqf>
-->[[publicVariable]] "_myLocalVariable"; {{cc|incorrect}}<br><br><!--
private _myLocalVariable = 33;
-->GlobalVariable {{=}} _myLocalVariable;<br><!--
publicVariable "_myLocalVariable"; // incorrect
-->[[publicVariable]] "GlobalVariable"; {{cc|correct}}</code>}}
 
GlobalVariable = _myLocalVariable;
publicVariable "GlobalVariable"; // correct
</sqf>
}}


=== Local Variables Scope ===
=== Local Variables Scope ===


{{Feature | Warning |
{{Feature|warning|
Local variables in [[call]]able code (e.g [[Arma 3 Functions Library|Functions]]) should be scoped using the command [[private]],
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.}}
otherwise you may modify local variables of the [[call]]ing script that are visible in the function.}}
<sqf>
// Since Arma 3 v1.54
private _myLocalVariable = 0;


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


If a [[private]] variable is initialised within a [[Control Structures|Control Structure]] (i.e. [[if]], [[for]], [[switch]], [[while]]),
If a [[private]] variable is initialised within a [[Control Structures|Control Structure]] (i.e. [[if]], [[for]], [[switch]], [[while]]),
Line 284: Line 294:
! style="width: 50%" | Incorrect
! style="width: 50%" | Incorrect
|-
|-
|<code>[[private]] _living = [[false]];<br><!--
| <sqf>
-->[[if]] ([[alive]] [[player]]) [[then]]<br><!--
private _living = false;
-->{<br><!--
if (alive player) then
--> _living = [[true]];<br><!--
{
-->};<br><br><br><!--
_living = true;
-->[[hint]] [[format]] ["%1", _living]; {{cc|returns [[true]]}}</code>
};
| <code><br>[[if]] ([[alive]] [[player]]) [[then]]<br><!--
 
-->{<br><!--
 
--> [[private]] _living = [[true]];<br><!--
hint format ["%1", _living]; // returns true
-->};<br><!--
</sqf>
-->{{cc|throws an error since the private variable was}}<br><!--
| <sqf>
-->{{cc|not initialised outside of the [[if]] control structure.}}<br><!--
// -
-->[[hint]] [[format]] ["%1", _living];</code>
if (alive player) then
{
private _living = true;
};
// throws an error since the private variable was
// not initialised outside of the if control structure.
hint format ["%1", _living];
</sqf>
|}
|}


Line 306: Line 323:


A variable is not strongly typed and changes its type according to the new data:
A variable is not strongly typed and changes its type according to the new data:
[[private]] "_myVariable"; {{cc|[[nil]]}}
<sqf>
_myVariable = '''{{Color|darkorange|1}}'''; {{cc|1 ([[Number]])}}
private "_myVariable"; // nil
_myVariable = {{Color|red|"test"}}; {{cc|"test" ([[String]])}}
_myVariable = 1; // 1 (Number)
_myVariable = "test"; // "test" (String)
</sqf>




Line 319: Line 338:


If you want to manually create a global function anyway, the best practice is the following:
If you want to manually create a global function anyway, the best practice is the following:
TAG_MyGlobalVariableFunction = [[compileFinal]] [[preprocessFileLineNumbers]] "functionFile.sqf";
<sqf>TAG_MyGlobalVariableFunction = compileFinal preprocessFileLineNumbers "functionFile.sqf";</sqf>


{{Feature | Informative | You should ideally run this code locally on every machine.
{{Feature|informative|
Using [[publicVariable]]  on a "final" global function (created with [[compileFinal]]) will indeed broadcast the variable '''and''' make it final on other clients as well, but the network can quickly become saturated from sending big pieces of code.}}
You should ideally run this code locally on every machine.
Using [[publicVariable]]  on a "final" global function (created with [[compileFinal]]) will indeed broadcast the variable '''and''' make it final on other clients as well, but the network can quickly become saturated from sending big pieces of code.
}}





Revision as of 14:51, 10 May 2022

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 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.

Variable deletion is done by setting its value to nil:

HugeVariable = nil;

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; // GlobalVariable is now 42 on the current machine but still 33 on the others publicVariable "GlobalVariable"; // updates the value to 42 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
BEGINNING OF FILE - e.g execVM "script.sqf";
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.
[] call {
hint str _myVariable; // works, as called code runs in the same scope
};
[_myVariable] spawn {
hint TAG_GlobalVariable; // works
hint str _myVariable; // throws an "undefined variable" error,
// as _myVariable does not exist in this new script
};
// trying to use _anotherVariable here would result in an "undefined variable" error,
// _anotherVariable being only scoped in the else block.
END OF FILE - TAG_GlobalVariable keeps on living in missionNamespace


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


Data Types

Variables may store values of a certain Data Types (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 should ideally run this code locally on every machine. Using publicVariable on a "final" global function (created with compileFinal) will indeed broadcast the variable and make it final on other clients as well, but the network can quickly become saturated from sending big pieces of code.


See also