Functions Library – Arma 3

From Bohemia Interactive Community
Jump to navigation Jump to search
m (Text replacement - " <nowiki>[</nowiki>" to " [<nowiki/>")
m (Some wiki formatting)
Line 1: Line 1:
[[Category:Arma 3: Editing]]
Arma 3 '''Functions Library''' is pack of routine script functions available from anywhere in game. Main difference from older [[Functions Library]] is that it runs automatically and doesn't require Functions manager to be present.


Arma 3 '''Functions Library''' is pack of routine script functions available from anywhere in game. Main difference from older [[Functions Library]] is that it runs automatically and doesn't require Functions manager to be present.


== Finding a Function ==
== Finding a Function ==
[[File:A3_functionwViewer.png|300px|thumb|right|Functions Viewer]]
[[File:A3_functionwViewer.png|300px|thumb|right|Functions Viewer]]
Before you can use a function, you first need to find it. The easiest way is to access the '''Functions Viewer''':
Before you can use a function, you first need to find it. The easiest way is to access the '''Functions Viewer''':
Line 18: Line 18:


All functions are also listed in [[:Category:Arma_3:_Functions|Arma 3 Functions]] category.
All functions are also listed in [[:Category:Arma_3:_Functions|Arma 3 Functions]] category.


== Calling a Function ==
== Calling a Function ==
Functions can be launched in mission, intro and outro using this [[call]] or [[spawn]] commands:
Functions can be launched in mission, intro and outro using this [[call]] or [[spawn]] commands:
  _returnedValue = ''arguments'' [[call]] ''functionName'';
  _returnedValue = ''arguments'' [[call]] ''functionName'';
Line 25: Line 27:


=== Arguments ===
=== Arguments ===
Arguments are data sent into the function, affecting its behavior.
Arguments are data sent into the function, affecting its behavior.


Line 41: Line 44:
  Ends mission with specific ending.
  Ends mission with specific ending.
   
   
  <span style="color:DarkCyan;">Parameter(s):
  {{Color|DarkCyan|Parameter(s):
  0 (Optional):
  0 (Optional):
  STRING - end name (default: "end1")
  STRING - end name (default: "end1")
Line 48: Line 51:
  2 (Optional):
  2 (Optional):
  BOOL - true for signature closing shot (default: true)
  BOOL - true for signature closing shot (default: true)
  NUMBER - duration of a simple fade out to black</span>
  NUMBER - duration of a simple fade out to black}}
   
   
  Returns:
  Returns:
Line 56: Line 59:
As you can see, all arguments are marked optional and you can call the function without them.
As you can see, all arguments are marked optional and you can call the function without them.


  [] call BIS_fnc_endMission;
  [] [[call]] [[BIS_fnc_endMission]];
:This will result in successfull ending of type "end1", preceeded with the signature [[Debriefing|closing shot]].
:This will result in successfull ending of type "end1", preceeded with the signature [[Debriefing|closing shot]].


  ["end2"] call BIS_fnc_endMission;
  ["end2"] [[call]] [[BIS_fnc_endMission]];
:Set the ending type to "end2", while keeping the other arguments intact.
:Set the ending type to "end2", while keeping the other arguments intact.


  ["end2", false, false] call BIS_fnc_endMission;
  ["end2", [[false]], [[false]]] [[call]] [[BIS_fnc_endMission]];
:Fail the mission without any effect, using "end2" type.
:Fail the mission without any effect, using "end2" type.


Line 68: Line 71:
However, what should you do if you want to set the '''only''' last argument without affecting the previous ones? The solution is simple - put an empty variable [[nil]] on their place.
However, what should you do if you want to set the '''only''' last argument without affecting the previous ones? The solution is simple - put an empty variable [[nil]] on their place.


  [<nowiki/>[[nil]], [[nil]], false] call BIS_fnc_endMission;
  [<nowiki/>[[nil]], [[nil]], [[false]]] [[call]] [[BIS_fnc_endMission]];
:Disable the closing effects, but keep the other aguments intact (successful "end1").
:Disable the closing effects, but keep the other aguments intact (successful "end1").


Line 74: Line 77:


=== Returned Value ===
=== Returned Value ===
Functions executed by [[call]] command can return back a value. Let's take a look at [[BIS_fnc_sideName]]:
Functions executed by [[call]] command can return back a value. Let's take a look at [[BIS_fnc_sideName]]:


Line 85: Line 89:
  0: SIDE or NUMBER - either side or side ID
  0: SIDE or NUMBER - either side or side ID
   
   
  <span style="color:DarkCyan;">Returns:
  {{Color|DarkCyan|Returns:
  STRING</span>
  STRING}}
  */
  */
The function returns a [[String]] - localized name of a side.
The function returns a [[String]] - localized name of a side.
  _westName = [[west]] call BIS_fnc_sideName;
  _westName = [[west]] [[call]] [[BIS_fnc_sideName]];
:Variable _westName will now be "BLUFOR" (or other name, based on selected language)
:Variable _westName will now be "BLUFOR" (or other name, based on selected language)


=== Multiplayer ===
=== Multiplayer ===
Functions executed using [[call]] or [[spawn]] command will run only on the computer which triggered them. If you'd wish to execute a function remotely on specific clients, use either [[remoteExec]] or [[remoteExecCall]].<br>
Functions executed using [[call]] or [[spawn]] command will run only on the computer which triggered them. If you'd wish to execute a function remotely on specific clients, use either [[remoteExec]] or [[remoteExecCall]].<br>
[arguments] [[remoteExec]] ["functionName",target,isPersistent];
[arguments] [[remoteExec]] ["functionName",target,isPersistent];


=== User Interface ===
=== User Interface ===
Anywhere outside of running mission, refer to the functions stored in [[uiNamespace]].
Anywhere outside of running mission, refer to the functions stored in [[uiNamespace]].
  ''arguments'' [[call]] ([[uiNamespace]] [[getVariable]] ''"functionName"'');
  ''arguments'' [[call]] ([[uiNamespace]] [[getVariable]] ''"functionName"'');
Line 115: Line 121:


=== Tag ===
=== Tag ===
Functions are configured within CfgFunctions class. To prevent duplicities, every author must create a subclass with unique ''tag'' and place functions inside it. The tag name will be used when composing a function name.
Functions are configured within CfgFunctions class. To prevent duplicities, every author must create a subclass with unique ''tag'' and place functions inside it. The tag name will be used when composing a function name.
  class CfgFunctions
  class CfgFunctions
  {
  {
  class <span style="color:green;">myTag</span>
  class {{Color|green|myTag}}
  {
  {
  class Anything
  class Anything
  {
  {
  tag = "<span style="color:green;">myTag</span>"; {{codecomment|//Custom tag name}}
  tag = "{{Color|green|myTag}}"; {{cc|Custom tag name}}
  requiredAddons[] = {"A3_Data_F"}; {{codecomment|//Optional requirements of CfgPatches classes. When some addons are missing, functions won't be compiled.}}
  requiredAddons[] = {"A3_Data_F"}; {{cc|Optional requirements of CfgPatches classes. When some addons are missing, functions won't be compiled.}}
  };
  };
  };
  };
Line 129: Line 136:


=== Path ===
=== Path ===
==== File Path ====
==== File Path ====
The easiest and the most transparent way is to set path for each function.
The easiest and the most transparent way is to set path for each function.
  class CfgFunctions
  class CfgFunctions
  {
  {
  class <span style="color:green;">myTag</span>
  class {{Color|green|myTag}}
  {
  {
  class myCategory
  class myCategory
  {
  {
  class <span style="color:teal;">myFunction</span> {file = "<span style="color:DarkOrange;">myFile.sqf</span>";};
  class {{Color|teal|myFunction}} {file = "{{Color|DarkOrange|myFile.sqf}}";};
  };
  };
  };
  };
  };
  };
This will try to compile function '''<big><span style="color:green;">myTag</span>_fnc_<span style="color:teal;">myFunction</span></big>''' from the following file:
This will try to compile function '''<big>{{Color|green|myTag}}_fnc_{{Color|teal|myFunction}}</big>''' from the following file:
  ''%ROOT%''\<span style="color:DarkOrange;">myFile.sqf</span>
  ''%ROOT%''\{{Color|DarkOrange|myFile.sqf}}
Where ''%ROOT%'' is either '''[[Mission_Editor:_External#Mission_Folder|mission root]]''' (where mission.sqm file is), or the '''game root''' (path to an addon is not included and has to be part of the file path, e.g., <span style="color:DarkOrange;">myAddon\myFile.sqf</span>).
Where ''%ROOT%'' is either '''[[Mission_Editor:_External#Mission_Folder|mission root]]''' (where mission.sqm file is), or the '''game root''' (path to an addon is not included and has to be part of the file path, e.g., {{Color|DarkOrange|myAddon\myFile.sqf}}).


==== Folder Path ====
==== Folder Path ====
Line 149: Line 157:
  class CfgFunctions
  class CfgFunctions
  {
  {
  class <span style="color:green;">myTag</span>
  class {{Color|green|myTag}}
  {
  {
  class myCategory
  class myCategory
  {
  {
  file = "<span style="color:DarkOrange;">myPath</span>";
  file = "{{Color|DarkOrange|myPath}}";
  class <span style="color:teal;">myFunction</span> {};
  class {{Color|teal|myFunction}} {};
  };
  };
  };
  };
  };
  };
Compile function '''<big><span style="color:green;">myTag</span>_fnc_<span style="color:teal;">myFunction</span></big>''' from the following file:
Compile function '''<big>{{Color|green|myTag}}_fnc_{{Color|teal|myFunction}}</big>''' from the following file:
  ''%ROOT%''\<span style="color:DarkOrange;">myPath</span>\fn_<span style="color:teal;">myFunction</span>.sqf
  ''%ROOT%''\{{Color|DarkOrange|myPath}}\fn_{{Color|teal|myFunction}}.sqf
<span style="color:DarkOrange;">myPath</span> can be a folder or multiple folders, e.g., <span style="color:DarkOrange;">myFolder\mySubfolder</span>
{{Color|DarkOrange|myPath}} can be a folder or multiple folders, e.g., {{Color|DarkOrange|myFolder\mySubfolder}}


==== Default Path (Mission Only) ====
==== Default Path (Mission Only) ====
Line 166: Line 174:
  class CfgFunctions
  class CfgFunctions
  {
  {
  class <span style="color:green;">myTag</span>
  class {{Color|green|myTag}}
  {
  {
  class <span style="color:crimson;">myCategory</span>
  class {{Color|crimson|myCategory}}
  {
  {
  class <span style="color:teal;">myFunction</span> {};
  class {{Color|teal|myFunction}} {};
  };
  };
  };
  };
  };
  };
Compile function '''<big><span style="color:green;">myTag</span>_fnc_<span style="color:teal;">myFunction</span></big>''' from the following file:
Compile function '''<big>{{Color|green|myTag}}_fnc_{{Color|teal|myFunction}}</big>''' from the following file:
  ''%ROOT%''\functions\<span style="color:crimson;">myCategory</span>\fn_<span style="color:teal;">myFunction</span>.sqf
  ''%ROOT%''\functions\{{Color|crimson|myCategory}}\fn_{{Color|teal|myFunction}}.sqf


=== Attributes ===
=== Attributes ===
Apart from already mentioned ''file'', function class can have additional attributes:
Apart from already mentioned ''file'', function class can have additional attributes:
  class CfgFunctions
  class CfgFunctions
  {
  {
  class <span style="color:green;">myTag</span>
  class {{Color|green|myTag}}
  {
  {
  class myCategory
  class myCategory
  {
  {
  class <span style="color:teal;">myFunction</span>
  class {{Color|teal|myFunction}}
  {
  {
  preInit = 1; {{codecomment|//(formerly known as "forced") 1 to call the function upon mission start, <u>before</u> objects are initialized. Passed arguments are ["preInit"]}}
  preInit = 1; {{cc|(formerly known as "forced") 1 to call the function upon mission start, <u>before</u> objects are initialized. Passed arguments are ["preInit"]}}
  postInit = 1; {{codecomment|//1 to call the function upon mission start, <u>after</u> objects are initialized. Passed arguments are ["postInit", didJIP]}}
  postInit = 1; {{cc|1 to call the function upon mission start, <u>after</u> objects are initialized. Passed arguments are ["postInit", didJIP]}}
  preStart = 1; {{codecomment|//1 to call the function upon game start, before title screen, but after all addons are loaded (config.cpp only)}}
  preStart = 1; {{cc|1 to call the function upon game start, before title screen, but after all addons are loaded (config.cpp only)}}
  ext = ".fsm"; {{codecomment|//Set file type, can be ".sqf" or ".fsm" (meaning scripted FSM). Default is ".sqf".}}
  ext = ".fsm"; {{cc|Set file type, can be ".sqf" or ".fsm" (meaning scripted FSM). Default is ".sqf".}}
  headerType = -1; {{codecomment|//Set function header type: -1 - no header; 0 - default header; 1 - system header.}}
  headerType = -1; {{cc|Set function header type: -1 - no header; 0 - default header; 1 - system header.}}
  recompile = 1; {{codecomment|//1 to recompile the function upon mission start (config.cpp only; functions in description.ext are compiled upon mission start already)}}
  recompile = 1; {{cc|1 to recompile the function upon mission start (config.cpp only; functions in description.ext are compiled upon mission start already)}}
  };
  };
  };
  };
  };
  };
  };
  };
All of these attributes are case sensitive.<br>
All of these attributes are case sensitive.


==== Pre and Post Init ====
==== Pre and Post Init ====
Line 263: Line 272:


=== Initialization Order ===
=== Initialization Order ===
''See [[Initialization_Order]]''
''See [[Initialization_Order]]''


== Writing a Function ==
== Writing a Function ==
The most important thing to remember when writing a function is that other people than you are going to use it. Most of them won't understand how does it work, expecting it to do its job without problems.
The most important thing to remember when writing a function is that other people than you are going to use it. Most of them won't understand how does it work, expecting it to do its job without problems.


Your function must be '''robust'''. It shouldn't allow passing arguments of incorrect [[Data Types]] in. When some values are incorrect, it should throw an error explaining what went wrong and how to fix it. And above all, its header must provide complete explanation of usage.
Your function must be '''robust'''. It shouldn't allow passing arguments of incorrect [[Data Types]] in. When some values are incorrect, it should throw an error explaining what went wrong and how to fix it. And above all, its header must provide complete explanation of usage.
{{Important|What is not documented, does not exist!}}
{{Important | What is not documented does not exist!}}


=== Loading Parameters ===
=== Loading Parameters ===
Arguments are the only way how to interact with your function. Let's now see how to make sure they are loaded properly.
Arguments are the only way how to interact with your function. Let's now see how to make sure they are loaded properly.


Line 282: Line 295:
| [[File:Ico_ok.png]]
| [[File:Ico_ok.png]]
|
|
  [player, position myCar] call myTag_fnc_myFunction;
  [<nowiki/>[[player]], [[position]] myCar] [[call]] myTag_fnc_myFunction;
|}
|}


Line 289: Line 302:
| [[File:Ico_none.png]]
| [[File:Ico_none.png]]
|
|
  [player] call myTag_fnc_myFunction;
  [<nowiki/>[[player]]] [[call]] myTag_fnc_myFunction;
|}
|}


Line 296: Line 309:
| [[File:Ico_none.png]]
| [[File:Ico_none.png]]
|
|
  [player, 0] call myTag_fnc_myFunction;
  [<nowiki/>[[player]], 0] [[call]] myTag_fnc_myFunction;
|}
|}


Line 303: Line 316:
| [[File:Ico_none.png]]
| [[File:Ico_none.png]]
|
|
  [player, [1, 2, 3, 4]] call myTag_fnc_myFunction;
  [<nowiki/>[[player]], [1, 2, 3, 4]] [[call]] myTag_fnc_myFunction;
|}
|}


Line 313: Line 326:


Rather than check for these exceptions yourself, you can use existing [[param]] command which will do it for you:
Rather than check for these exceptions yourself, you can use existing [[param]] command which will do it for you:
  _unit = param [<span style="color:darkorange;">0</span>, <span style="color:teal;">objNull</span>, <span style="color:crimson;">[objNull]</span>];
  _unit = [[param]] [{{Color|darkorange|0}}, {{Color|teal|objNull}}, {{Color|crimson|[objNull]}}];
For multiple parameters, use the [[params]] command instead.
For multiple parameters, use the [[params]] command instead.
  params [[<span style="color:green;">"_unit"</span>, <span style="color:teal;">objNull</span>, <span style="color:crimson;">[objNull]</span>], [<span style="color:green;">"_target"</span>, <span style="color:teal;">[0, 0, 0]</span>, <span style="color:crimson;">[[], objNull]</span>, <span style="color:indigo;">[2, 3]</span>]];
  [[params]] [
  _unit doWatch _target;
[{{Color|green|"_unit"}}, {{Color|teal|objNull}}, {{Color|crimson|[objNull]}}],
* In a [[params]] array first argument is the name of the <span style="color:green;">'''private variable'''</span>. In [[param]] it's the <span style="color:darkorange;">'''index'''</span> number.
[{{Color|green|"_target"}}, {{Color|teal|[0, 0, 0]}}, {{Color|crimson|[[], objNull]}}, {{Color|indigo|[2, 3]}}]
* Second argument is the <span style="color:teal;">'''default value'''</span>. It will be used when the argument is missing, is [[nil]] or when wrong data type is used.
];
* Next is optional <span style="color:crimson;">'''array of compatible data types'''</span>. They are defined by an example of the type, e.g. [[objNull]] will mean an object is allowed. When wrong data type is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.
  _unit [[doWatch]] _target;
* The last, also optional argument is an <span style="color:indigo;">'''array of required array sizes'''</span>. [2,3] means only array with 2 or 3 elements are allowed. When incorrectly large array is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.
* In a [[params]] array first argument is the name of the '''{{Color|green|private variable}}'''. In [[param]] it's the '''{{Color|darkorange|index}}''' number.
* Second argument is the '''{{Color|teal|default value}}'''. It will be used when the argument is missing, is [[nil]] or when wrong data type is used.
* Next is optional '''{{Color|crimson|array of compatible data types}}'''. They are defined by an example of the type, e.g. [[objNull]] will mean an object is allowed. When wrong data type is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.
* The last, also optional argument is an '''{{Color|indigo|array of required array sizes}}'''. [2,3] means only array with 2 or 3 elements are allowed. When incorrectly large array is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.




Line 327: Line 343:
| [[File:Ico_ok.png]]
| [[File:Ico_ok.png]]
|
|
  [player] call myTag_fnc_myFunction;
  [<nowiki/>[[player]]] [[call]] myTag_fnc_myFunction;
|}
|}
: ''_target'' is undefined. Default <span style="color:teal;">[0, 0, 0]</span> is used instead. No error message is logged.
: ''_target'' is undefined. Default {{Color|teal|[0, 0, 0]}} is used instead. No error message is logged.


{|
{|
| [[File:Ico_ok.png]]
| [[File:Ico_ok.png]]
|
|
  [nil, position myCar] call myTag_fnc_myFunction;
  [<nowiki/>[[nil]], [[position]] myCar] [[call]] myTag_fnc_myFunction;
|}
|}
: ''_unit'' is undefined (nil is passed instead). Default <span style="color:teal;">objNull</span> is used instead. No error message is logged.
: ''_unit'' is undefined (nil is passed instead). Default {{Color|teal|objNull}} is used instead. No error message is logged.


{|
{|
| [[File:Ico_warning.png]]
| [[File:Ico_warning.png]]
|
|
  [player, 0] call myTag_fnc_myFunction;
  [<nowiki/>[[player]], 0] [[call]] myTag_fnc_myFunction;
|}
|}
: ''_target'' has wrong <span style="color:crimson;">type</span>. Default <span style="color:teal;">[0, 0, 0]</span> is used instead. Error message is logged.
: ''_target'' has wrong {{Color|crimson|type}}. Default {{Color|teal|[0, 0, 0]}} is used instead. Error message is logged.


{|
{|
| [[File:Ico_warning.png]]
| [[File:Ico_warning.png]]
|
|
  [player, [1, 2, 3, 4]] call myTag_fnc_myFunction;
  [<nowiki/>[[player]], [1, 2, 3, 4]] [[call]] myTag_fnc_myFunction;
|}
|}
: ''_target'' has wrong <span style="color:indigo;">size</span>. Default <span style="color:teal;">[0, 0, 0]</span> is used instead. Error message is logged.
: ''_target'' has wrong {{Color|indigo|size}}. Default {{Color|teal|[0, 0, 0]}} is used instead. Error message is logged.




Line 357: Line 373:
| [[File:Ico_ok.png]]
| [[File:Ico_ok.png]]
|
|
  player call myTag_fnc_myFunction;
  [[player]] [[call]] myTag_fnc_myFunction;
|}
|}


=== Returning Value ===
=== Returning Value ===
Users will often save result of your function to a variable. If no value is returned, the variable would be [[nil]] and could lead to script errors.
Users will often save result of your function to a variable. If no value is returned, the variable would be [[nil]] and could lead to script errors.
  _myVar = [player, position myCar] call myTag_fnc_myFunction;
  _myVar = [<nowiki/>[[player]], [[position]] myCar] [[call]] myTag_fnc_myFunction;


It's good practice to '''always''' return a value, even if it would be simple [[true]] marking the function as completed. Let's use the example function from above:
It's good practice to '''always''' return a value, even if it would be simple [[true]] marking the function as completed. Let's use the example function from above:
  params [["_unit", objNull, [objNull]], ["_target", [0, 0, 0], [[], objNull], [2, 3]]];
  [[params]] [
  _unit doWatch _target;
["_unit", [[objNull]], [objNull]],
  '''true'''
["_target", [0, 0, 0], [[], [[objNull]]], [2, 3]]
];
  _unit [[doWatch]] _target;
  '''[[true]]'''


=== Showing Errors ===
=== Showing Errors ===
While [[param]] and [[params]] can filter out the most common issues, sometimes your function will have special rules which will need to be handled. Let's return back to our example function, where we'd want to terminate the function with error when ''_unit'' is dead:
While [[param]] and [[params]] can filter out the most common issues, sometimes your function will have special rules which will need to be handled. Let's return back to our example function, where we'd want to terminate the function with error when ''_unit'' is dead:
  params [["_unit", objNull, [objNull]], ["_target", [0, 0, 0], [[], objNull], [2, 3]]];
  [[params]] [["_unit", [[objNull]], [objNull]], ["_target", [0, 0, 0], [[], [[objNull]]], [2, 3]]];
  '''if (!alive _unit) exitwith {["Unit %1 must be alive.", _unit] call [[BIS_fnc_error]]; false};'''
  '''[[if]] (![[alive]] _unit) [[exitwWth]] { ["Unit %1 must be alive.", _unit] [[call]] [[BIS_fnc_error]]; [[false]] };'''
  _unit doWatch _target;
  _unit [[doWatch]] _target;
  true
  [[true]]
Notice that we're returning [[false]] at the end of [[exitWith]] code.
Notice that we're returning [[false]] at the end of [[exitWith]] code.
{{Important|Error states must always return value of the same type as when everything is fine ([[Boolean]] in this case).}}
{{Important|Error states must always return value of the same type as when everything is fine ([[Boolean]] in this case).}}




BIS_fnc_error accepts [[String]] and [[Array]] of [[format]]ted ext. The error is logged into [[RPT]] and if the mission is previewd from the editor, it will also appear on screen.
[[BIS_fnc_error]] accepts [[String]] and [[Array]] of [[format]]ted ext. The error is logged into [[RPT]] and if the mission is previewd from the editor, it will also appear on screen.
{|
{|
| [[RPT]]
| [[RPT]]
Line 390: Line 411:


=== Logging ===
=== Logging ===
Apart from errors, you can print any debug message you need. Use one of the following functions:
Apart from errors, you can print any debug message you need. Use one of the following functions:
* [[BIS_fnc_log]] - log a data of any type (e.g., [[String]], [[Number]], [[Object]], ...)
* [[BIS_fnc_log]] - log a data of any type (e.g., [[String]], [[Number]], [[Object]], ...)
Line 402: Line 424:
|-
|-
|
|
  <span style="color:green;">"Hello World"</span> call BIS_fnc_log;
  {{Color|green|"Hello World"}} [[call]] [[BIS_fnc_log]];
|
|
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] <span style="color:green;">Hello World</span>"
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] {{Color|green|Hello World}}"
|-
|-
|
|
  <span style="color:green;">42</span> call BIS_fnc_log;
  {{Color|green|42}} [[call]] [[BIS_fnc_log]];
|
|
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] <span style="color:green;">42</span>"
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] {{Color|green|42}}"
|-
|-
|
|
  [<span style="color:green;">"I'm playing %1"</span>, [[missionName]]] call BIS_fnc_logFormat;
  [{{Color|green|"I'm playing %1"}}, [[missionName]]] [[call]] [[BIS_fnc_logFormat]];
|
|
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] <span style="color:green;">I'm playing FalconWing</span>"
  "User1/BIS_fnc_log: [myTag_fnc_myFunction] {{Color|green|I'm playing FalconWing}}"
|}
|}




To prevent RPT spam, logging is by default enabled only when previewing a mission from the editor. To force it in the mission everywhere, use the following [[Description.ext]] attribute:
To prevent RPT spam, logging is by default enabled only when previewing a mission from the editor. To force it in the mission everywhere, use the following [[Description.ext]] attribute:
allowFunctionsLog = 1;
<syntaxhighlight lang="cpp">
allowFunctionsLog = 1;
</syntaxhighlight>


=== Recompiling ===
=== Recompiling ===
Once compiled, functions remain unchanged and editing their file won't have any effect in the game. To adjust functions on the fly, you can manually trigger their recompilation.
Once compiled, functions remain unchanged and editing their file won't have any effect in the game. To adjust functions on the fly, you can manually trigger their recompilation.
  1 call [[BIS_fnc_recompile]];
  1 [[call]] [[BIS_fnc_recompile]];
:Recompiles all functions. Can be also achieved by clicking on RECOMPILE button in the Functions Viewer
:Recompiles all functions. Can be also achieved by clicking on RECOMPILE button in the Functions Viewer
  "''functionName''" call [[BIS_fnc_recompile]];
  "''functionName''" [[call]] [[BIS_fnc_recompile]];
:Recompile the given function
:Recompile the given function


As a security measure, functions are by default protected against rewriting during the mission. <u>This restriction does not apply in missions previewed from the editor and in missions with the following attribute in [[Description.ext]]</u>:
As a security measure, functions are by default protected against rewriting during the mission. <u>This restriction does not apply in missions previewed from the editor and in missions with the following attribute in [[Description.ext]]</u>:
allowFunctionsRecompile = 1;
<syntaxhighlight lang="cpp">
allowFunctionsRecompile = 1;
</syntaxhighlight>


"Recompile" button in the functions viewer will be enabled only when recompiling is allowed.
"Recompile" button in the functions viewer will be enabled only when recompiling is allowed.


=== Meta Variables ===
=== Meta Variables ===
System is adding header with basic meta data to all functions. Following local variables are declared there:
System is adding header with basic meta data to all functions. Following local variables are declared there:
* '''_fnc_scriptName''': [[String]] - Function name (e.g., myTag_fnc_myFunction)
* '''_fnc_scriptName''': [[String]] - Function name (e.g., myTag_fnc_myFunction)
Line 451: Line 479:
{{Important|Function recompiling has to be allowed!}}
{{Important|Function recompiling has to be allowed!}}
-->
-->
[[Category:Arma 3: Editing]]

Revision as of 00:03, 6 July 2020

Arma 3 Functions Library is pack of routine script functions available from anywhere in game. Main difference from older Functions Library is that it runs automatically and doesn't require Functions manager to be present.


Finding a Function

Functions Viewer

Before you can use a function, you first need to find it. The easiest way is to access the Functions Viewer:

  • In editor, click on icon editor functions.png icon or press Ctrl + F
  • In mission, access the debug console (automatically visible in pause menu of an editor mission) and click on FUNCTIONS button.

Once in the Functions Viewer, you can filter all available functions by location, projects and categories.

When you find the desired function, look at the code preview on the right. Every function has a header where you can find basic description of its functionality including required arguments, returned values and sometimes examples of use.

Template:note


All functions are also listed in Arma 3 Functions category.


Calling a Function

Functions can be launched in mission, intro and outro using this call or spawn commands:

_returnedValue = arguments call functionName;
arguments spawn functionName;

Arguments

Arguments are data sent into the function, affecting its behavior.

They can be mandatory or optional.

  • Mandatory arguments are required for function to run. When missing, the function usually stops and throws an error.
  • Optional arguments allows more detailed configuration. If you dont send them, the function will use pre-defined default values.

Template:note


For example, let's take a look at BIS_fnc_endMission, a function which ends a mission with animated closing shot. This is what the header says:

/*
	Author: Karel Moricky

	Description:
	Ends mission with specific ending.

	Parameter(s):
		0 (Optional):
			STRING - end name (default: "end1")
			ARRAY in format [endName,ID], will be composed to "endName_ID" string
		1 (Optional): BOOL - true to end mission, false to fail mission (default: true)
		2 (Optional):
			BOOL - true for signature closing shot (default: true)
			NUMBER - duration of a simple fade out to black

	Returns:
	BOOL
*/

As you can see, all arguments are marked optional and you can call the function without them.

[] call BIS_fnc_endMission;
This will result in successfull ending of type "end1", preceeded with the signature closing shot.
["end2"] call BIS_fnc_endMission;
Set the ending type to "end2", while keeping the other arguments intact.
["end2", false, false] call BIS_fnc_endMission;
Fail the mission without any effect, using "end2" type.


However, what should you do if you want to set the only last argument without affecting the previous ones? The solution is simple - put an empty variable nil on their place.

[nil, nil, false] call BIS_fnc_endMission;
Disable the closing effects, but keep the other aguments intact (successful "end1").

Template:note

Returned Value

Functions executed by call command can return back a value. Let's take a look at BIS_fnc_sideName:

/*
	Author: Karel Moricky

	Description:
	Returns side name

	Parameter(s):
	0: SIDE or NUMBER - either side or side ID

	Returns:
	STRING
*/

The function returns a String - localized name of a side.

_westName = west call BIS_fnc_sideName;
Variable _westName will now be "BLUFOR" (or other name, based on selected language)

Multiplayer

Functions executed using call or spawn command will run only on the computer which triggered them. If you'd wish to execute a function remotely on specific clients, use either remoteExec or remoteExecCall.
[arguments] remoteExec ["functionName",target,isPersistent];

User Interface

Anywhere outside of running mission, refer to the functions stored in uiNamespace.

arguments call (uiNamespace getVariable "functionName");

Adding a Function

When writing a script, consider registering it into the Functions Library.

Main benefits:

  1. Automatic compilation upon mission start into a global variable - no need to remember direct paths to files.
  2. Anti-hack protection using compileFinal (see Recompiling for more info)
  3. Listing in the Functions Viewer
  4. Advanced debugging options
  5. Optional immediate execution upon mission start, without need for manual call
  6. Potential performance improvements


Mission and campaign specific functions can be configured in Description.ext, while addon functions are defined in Config.cpp. Configuration structure is the same in both cases.

Tag

Functions are configured within CfgFunctions class. To prevent duplicities, every author must create a subclass with unique tag and place functions inside it. The tag name will be used when composing a function name.

class CfgFunctions
{
	class myTag
	{
		class Anything
		{
			tag = "myTag"; // Custom tag name
			requiredAddons[] = {"A3_Data_F"}; // Optional requirements of CfgPatches classes. When some addons are missing, functions won't be compiled.
		};
	};
};

Path

File Path

The easiest and the most transparent way is to set path for each function.

class CfgFunctions
{
	class myTag
	{
		class myCategory
		{
			class myFunction {file = "myFile.sqf";};
		};
	};
};

This will try to compile function myTag_fnc_myFunction from the following file:

%ROOT%\myFile.sqf

Where %ROOT% is either mission root (where mission.sqm file is), or the game root (path to an addon is not included and has to be part of the file path, e.g., myAddon\myFile.sqf).

Folder Path

You can set folder path and leave the function paths undefined. The functions will then be loaded from the folder.

class CfgFunctions
{
	class myTag
	{
		class myCategory
		{
			file = "myPath";
			class myFunction {};
		};
	};
};

Compile function myTag_fnc_myFunction from the following file:

%ROOT%\myPath\fn_myFunction.sqf

myPath can be a folder or multiple folders, e.g., myFolder\mySubfolder

Default Path (Mission Only)

In a mission, you can leave also the folder path undefined and let functions be loaded from the default directory.

class CfgFunctions
{
	class myTag
	{
		class myCategory
		{
			class myFunction {};
		};
	};
};

Compile function myTag_fnc_myFunction from the following file:

%ROOT%\functions\myCategory\fn_myFunction.sqf

Attributes

Apart from already mentioned file, function class can have additional attributes:

class CfgFunctions
{
	class myTag
	{
		class myCategory
		{
			class myFunction
			{
				preInit = 1;		// (formerly known as "forced") 1 to call the function upon mission start, before objects are initialized. Passed arguments are ["preInit"]
				postInit = 1;		// 1 to call the function upon mission start, after objects are initialized. Passed arguments are ["postInit", didJIP]
				preStart = 1;		// 1 to call the function upon game start, before title screen, but after all addons are loaded (config.cpp only)
				ext = ".fsm";		// Set file type, can be ".sqf" or ".fsm" (meaning scripted FSM). Default is ".sqf".
				headerType = -1;	// Set function header type: -1 - no header; 0 - default header; 1 - system header.
				recompile = 1;		// 1 to recompile the function upon mission start (config.cpp only; functions in description.ext are compiled upon mission start already)
			};
		};
	};
};

All of these attributes are case sensitive.

Pre and Post Init

preInit and postInit attributes are truly powerful ones, as they let you execute your function at the beginning of every mission. Use them with caution!.
preInit are called unscheduled so suspension is not allowed. Parameters passed are [ "preInit" ].
postInit are called scheduled so suspension is allowed but any long term suspension will halt the mission loading until suspension has finished. Parameters passed are [ "postInit", didJIP ].

  • Any scripting error will prevent the mission from being loaded correctly
  • Server admins might blacklist your addon if they find out you're using the function for hacking.

Initialization Order

See Initialization_Order


Writing a Function

The most important thing to remember when writing a function is that other people than you are going to use it. Most of them won't understand how does it work, expecting it to do its job without problems.

Your function must be robust. It shouldn't allow passing arguments of incorrect Data Types in. When some values are incorrect, it should throw an error explaining what went wrong and how to fix it. And above all, its header must provide complete explanation of usage.

What is not documented does not exist!

Loading Parameters

Arguments are the only way how to interact with your function. Let's now see how to make sure they are loaded properly.

We have this very simple function which will let a unit watch a position:

params ["_unit", "_target"];
_unit doWatch _target;

Expected way how to call the function is by correctly defining all arguments:

Ico ok.png
[player, position myCar] call myTag_fnc_myFunction;

However, the function will break down when you try to send only one argument in:

Ico none.png
[player] call myTag_fnc_myFunction;

Furthermore, using wrong data type will also lead to a problem:

Ico none.png
[player, 0] call myTag_fnc_myFunction;

Variabe _target expects position array in format [x,y,z]. Scripting error will appear when different number of elements is used:

Ico none.png
[player, [1, 2, 3, 4]] call myTag_fnc_myFunction;


As you can see there, the most common problems are:

  1. Param of wrong data type is sent
  2. Param is missing
  3. Param is an array expecting specific number of elements, but different number is sent

Rather than check for these exceptions yourself, you can use existing param command which will do it for you:

_unit = param [0, objNull, [objNull]];

For multiple parameters, use the params command instead.

params [
	["_unit", objNull, [objNull]],
	["_target", [0, 0, 0], {{Color|crimson|[[], objNull]}}, [2, 3]]
];
_unit doWatch _target;
  • In a params array first argument is the name of the private variable. In param it's the index number.
  • Second argument is the default value. It will be used when the argument is missing, is nil or when wrong data type is used.
  • Next is optional array of compatible data types. They are defined by an example of the type, e.g. objNull will mean an object is allowed. When wrong data type is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.
  • The last, also optional argument is an array of required array sizes. [2,3] means only array with 2 or 3 elements are allowed. When incorrectly large array is sent into your function, BIS_fnc_param will log an error message explaining what went wrong and use the default value.


Let's see what will happen when you try to use the wrong examples now:

Ico ok.png
[player] call myTag_fnc_myFunction;
_target is undefined. Default [0, 0, 0] is used instead. No error message is logged.
Ico ok.png
[nil, position myCar] call myTag_fnc_myFunction;
_unit is undefined (nil is passed instead). Default objNull is used instead. No error message is logged.
Ico warning.png
[player, 0] call myTag_fnc_myFunction;
_target has wrong type. Default [0, 0, 0] is used instead. Error message is logged.
Ico warning.png
[player, [1, 2, 3, 4]] call myTag_fnc_myFunction;
_target has wrong size. Default [0, 0, 0] is used instead. Error message is logged.


Additionally, when only one argument is used, you can send it into the function directly without need to have it in an array.

Ico ok.png
player call myTag_fnc_myFunction;

Returning Value

Users will often save result of your function to a variable. If no value is returned, the variable would be nil and could lead to script errors.

_myVar = [player, position myCar] call myTag_fnc_myFunction;

It's good practice to always return a value, even if it would be simple true marking the function as completed. Let's use the example function from above:

params [
	["_unit", objNull, [objNull]],
	["_target", [0, 0, 0], [[], objNull], [2, 3]]
];
_unit doWatch _target;
true

Showing Errors

While param and params can filter out the most common issues, sometimes your function will have special rules which will need to be handled. Let's return back to our example function, where we'd want to terminate the function with error when _unit is dead:

params [["_unit", objNull, [objNull]], ["_target", [0, 0, 0], [[], objNull], [2, 3]]];
if (!alive _unit) exitwWth { ["Unit %1 must be alive.", _unit] call BIS_fnc_error; false };
_unit doWatch _target;
true

Notice that we're returning false at the end of exitWith code.

Error states must always return value of the same type as when everything is fine (Boolean in this case).


BIS_fnc_error accepts String and Array of formatted ext. The error is logged into RPT and if the mission is previewd from the editor, it will also appear on screen.

RPT
"User1/log: ERROR: [BIS_fnc_respawnTickets] #0: 0 is type SCALAR, must be NAMESPACE, SIDE, GROUP, OBJECT, BOOL. true used instead."
In-game On-screen error

Logging

Apart from errors, you can print any debug message you need. Use one of the following functions:

Profile name and function name will automatically appear in the output text, helping you identify the source.


Usage examples:

Expression RPT Output
"Hello World" call BIS_fnc_log;
"User1/BIS_fnc_log: [myTag_fnc_myFunction] Hello World"
42 call BIS_fnc_log;
"User1/BIS_fnc_log: [myTag_fnc_myFunction] 42"
["I'm playing %1", missionName] call BIS_fnc_logFormat;
"User1/BIS_fnc_log: [myTag_fnc_myFunction] I'm playing FalconWing"


To prevent RPT spam, logging is by default enabled only when previewing a mission from the editor. To force it in the mission everywhere, use the following Description.ext attribute:

allowFunctionsLog = 1;

Recompiling

Once compiled, functions remain unchanged and editing their file won't have any effect in the game. To adjust functions on the fly, you can manually trigger their recompilation.

1 call BIS_fnc_recompile;
Recompiles all functions. Can be also achieved by clicking on RECOMPILE button in the Functions Viewer
"functionName" call BIS_fnc_recompile;
Recompile the given function

As a security measure, functions are by default protected against rewriting during the mission. This restriction does not apply in missions previewed from the editor and in missions with the following attribute in Description.ext:

allowFunctionsRecompile = 1;

"Recompile" button in the functions viewer will be enabled only when recompiling is allowed.

Meta Variables

System is adding header with basic meta data to all functions. Following local variables are declared there:

  • _fnc_scriptName: String - Function name (e.g., myTag_fnc_myFunction)
  • _fnc_scriptNameParent: String - Name of q function from which the current one was called (_fnc_scriptName used when not defined)
Do not modify these values!