Introduction to Arma Scripting: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
m (Adjusted introduction)
m (Switched to <sqf inline>)
Line 18: Line 18:
== Variables ==
== Variables ==
[[Variables]] are a fundamental building block of scripting (and programming in general). Like in mathematics, they serve as placeholders for values. A few examples:
[[Variables]] are a fundamental building block of scripting (and programming in general). Like in mathematics, they serve as placeholders for values. A few examples:
* {{ic|A {{=}} 1;}} The variable <var>A</var> now has the value 1.
* <sqf inline>A = 1;</sqf> The variable <var>A</var> now has the value 1.
* {{ic|B {{=}} 2;}} The variable <var>B</var> now has the value 2.
* <sqf inline>B = 2;</sqf> The variable <var>B</var> now has the value 2.
* {{ic|C {{=}} "Hello World!";}} The variable <var>C</var> now has the value "Hello World!".
* <sqf inline>C = "Hello World!";</sqf> The variable <var>C</var> now has the value "Hello World!".
A variable always has a [[Data Types|Data Type]]. In the example above, the variables <var>A</var> and <var>B</var> both have the data type [[Number]], while <var>C</var> has the data type [[String]]. The data type of a variable is not fixed and changes automatically based on the current value of the variable.
A variable always has a [[Data Types|Data Type]]. In the example above, the variables <var>A</var> and <var>B</var> both have the data type [[Number]], while <var>C</var> has the data type [[String]]. The data type of a variable is not fixed and changes automatically based on the current value of the variable.




== Commands and Operators ==
== Commands and Operators ==
Two other basic tools of scripting are commands and [[Operators]]. In fact, they are so basic that the examples in the {{HashLink|#Variables}} section above already had to make use of an operator: The equals sign ({{ic|[[a = b|=]]}}) serves as the assignment operator, assigning values to variables. Similarly, symbols such as {{ic|[[+]]}}, {{ic|[[-]]}}, {{ic|[[a * b|*]]}} and {{ic|[[a / b|/]]}} are also operators. Using operators is quite simple:
Two other basic tools of scripting are commands and [[Operators]]. In fact, they are so basic that the examples in the {{HashLink|#Variables}} section above already had to make use of an operator: The equals sign (<sqf inline>=</sqf>) serves as the assignment operator, assigning values to variables. Similarly, symbols such as <sqf inline>+</sqf>, <sqf inline>-</sqf>, <sqf inline>*</sqf> and <sqf inline>/</sqf> are also operators. Using operators is quite simple:
<sqf>
<sqf>
A = 1.5;
A = 1.5;
Line 49: Line 49:


=== Conditions ===
=== Conditions ===
In the example above, the condition is {{ic|[[damage]] [[player]] > 0.5}}. Like all conditions, it results in a [[Boolean]] value when evaluated:
In the example above, the condition is <sqf inline>damage player > 0.5</sqf>. Like all conditions, it results in a [[Boolean]] value when evaluated:
# First, {{ic|[[damage]] [[player]]}} is evaluated and returns a number.
# First, <sqf inline>damage player</sqf> is evaluated and returns a number.
# Then, the {{ic|>}} operator compares that number to 0.5:
# Then, the <sqf inline>></sqf> operator compares that number to 0.5:
#* If the number is greater than 0.5, the {{ic|>}} operator returns [[true]].
#* If the number is greater than 0.5, the <sqf inline>></sqf> operator returns [[true]].
#* If the number is less than or equal to 0.5, the {{ic|>}} operator returns [[false]].
#* If the number is less than or equal to 0.5, the <sqf inline>></sqf> operator returns [[false]].


=== Booleans ===
=== Booleans ===
Line 65: Line 65:
! Operation !! Description !! SQF Operator !! SQF Command
! Operation !! Description !! SQF Operator !! SQF Command
|-
|-
| NOT (Negation) || Inverts the input value. || style="text-align: center" | {{ic|!}} || style="text-align: center" | [[not]]
| NOT (Negation) || Inverts the input value. || style="text-align: center" | <sqf inline>!</sqf> || style="text-align: center" | [[not]]
|-
|-
| AND (Conjunction) || Combines two Booleans into one. Only returns [[true]] if both input values are [[true]]. || style="text-align: center" | {{ic|&&}} || style="text-align: center" | [[and]]
| AND (Conjunction) || Combines two Booleans into one. Only returns [[true]] if both input values are [[true]]. || style="text-align: center" | <sqf inline>&&</sqf> || style="text-align: center" | [[and]]
|-
|-
| OR (Disjunction) || Combines two Booleans into one. Returns [[true]] if at least one of the input values is [[true]]. || style="text-align: center" | {{ic|<nowiki>||</nowiki>}} || style="text-align: center" | [[or]]
| OR (Disjunction) || Combines two Booleans into one. Returns [[true]] if at least one of the input values is [[true]]. || style="text-align: center" | <sqf inline>||</sqf> || style="text-align: center" | [[or]]
|}
|}


Line 81: Line 81:
! Expression !! Result
! Expression !! Result
|-
|-
| {{ic|![[true]]}} || [[false]]
| <sqf inline>!true</sqf> || [[false]]
|-
|-
| {{ic|![[false]]}} || [[true]]
| <sqf inline>!false</sqf> || [[true]]
|}
|}


Line 92: Line 92:
! Expression !! Result
! Expression !! Result
|-
|-
| {{ic|[[true]] && [[true]]}} || [[true]]
| <sqf inline>true && true</sqf> || [[true]]
|-
|-
| {{ic|[[true]] && [[false]]}} || [[false]]
| <sqf inline>true && false</sqf> || [[false]]
|-
|-
| {{ic|[[false]] && [[true]]}} || [[false]]
| <sqf inline>false && true</sqf> || [[false]]
|-
|-
| {{ic|[[false]] && [[false]]}} || [[false]]
| <sqf inline>false && false</sqf> || [[false]]
|}
|}


Line 107: Line 107:
! Expression !! Result
! Expression !! Result
|-
|-
| {{ic|[[true]] <nowiki>||</nowiki> [[true]]}} || [[true]]
| <sqf inline>true || true</sqf> || [[true]]
|-
|-
| {{ic|[[true]] <nowiki>||</nowiki> [[false]]}} || [[true]]
| <sqf inline>true || false</sqf> || [[true]]
|-
|-
| {{ic|[[false]] <nowiki>||</nowiki> [[true]]}} || [[true]]
| <sqf inline>false || true</sqf> || [[true]]
|-
|-
| {{ic|[[false]] <nowiki>||</nowiki> [[false]]}} || [[false]]
| <sqf inline>false || false</sqf> || [[false]]
|}
|}
</div>
</div>
Line 125: Line 125:
</sqf>
</sqf>


{{Feature|Informative|Beginners sometimes write conditions such as {{ic|[[if]] (Condition [[==]] [[true]])}} or {{ic|[[if]] (Condition [[==]] [[false]])}}.<br>
{{Feature|Informative|Beginners sometimes write conditions such as <sqf inline>if (Condition == true)</sqf> or <sqf inline>if (Condition == false)</sqf>.<br>
While doing so is not a real error, it is unnecessary because [[Control Structures]] (and [[Trigger]]s) always implicitly compare the condition to [[true]].<br>
While doing so is not a real error, it is unnecessary because [[Control Structures]] (and [[Trigger]]s) always implicitly compare the condition to [[true]].<br>
The correct (as in faster, more common and more readable) way to write such conditions is {{ic|[[if]] (Condition)}} and {{ic|[[if]] (!Condition)}} respectively.
The correct (as in faster, more common and more readable) way to write such conditions is <sqf inline>if (Condition)</sqf> and <sqf inline>if (!Condition)</sqf> respectively.
}}
}}



Revision as of 17:37, 10 July 2022

🏗
This article is a work in progress!

Scripting is one of the most powerful and most versatile tools available in the Arma sandbox. Unfortunately, it is also one of the most complex and unforgiving aspects of addon (mod) and mission creation.

Arma 3, Arma 2, Armed Assault and Arma: Cold War Assault all use a scripting language called SQF. Its predecessor SQS has been considered deprecated since Armed Assault (2006) and is no longer used. As of Arma Reforger (2022), SQF has been succeeded by Enforce Script. This introduction only considers SQF.


Scripting Topics

There is a plethora of topics to learn about in the context of Arma scripting (see the table below). Fortunately, there is no need to acquire detailed knowledge about all of these things in order to get started with scripting. To aid with prioritization, this page provides three selections of topics, each relevant to beginner, intermediate and advanced scripters respectively.

Real Virtuality Scripting
Terminology ArgumentIdentifierExpressionOperandOperatorsParameterStatementVariablesMagic VariablesFunction
Syntax SQF SyntaxSQS SyntaxOrder of PrecedenceControl Structures
Tutorials Introduction to Arma ScriptingCode Best PracticesExample CodeCode OptimisationMission OptimisationMultiplayer ScriptingSQS → SQF
Data Types General ArrayBooleanCodeConfigControlDiary RecordDisplayEden EntityEden IDEditor ObjectGroupHashMapLocationNamespaceNumberObjectScript Handle
SideStringStructured TextTaskTeamTeam MemberNaNAnythingNothingVoidSwitch TypeWhile TypeWith TypeFor TypeIf Type
Special Arrays Array of Eden EntitiesColorDateParticleArrayPositionUnit Loadout ArrayVector3DWaypoint
Scripting Commands Scripting CommandsScripting Commands by Functionality
Scripting Functions Scripting FunctionsFunctions by Functionality
Debugging Common Scripting ErrorsDebugging TechniquesException handling
Advanced Event ScriptsEvent HandlersPreProcessor CommandsInitialisation OrderPerformance Profiling


Beginner Scripting

Variables

Variables are a fundamental building block of scripting (and programming in general). Like in mathematics, they serve as placeholders for values. A few examples:

  • A = 1; The variable A now has the value 1.
  • B = 2; The variable B now has the value 2.
  • C = "Hello World!"; The variable C now has the value "Hello World!".

A variable always has a Data Type. In the example above, the variables A and B both have the data type Number, while C has the data type String. The data type of a variable is not fixed and changes automatically based on the current value of the variable.


Commands and Operators

Two other basic tools of scripting are commands and Operators. In fact, they are so basic that the examples in the Variables section above already had to make use of an operator: The equals sign (=) serves as the assignment operator, assigning values to variables. Similarly, symbols such as +, -, * and / are also operators. Using operators is quite simple:

A = 1.5; B = -2 * A; C = A + B + 3.5; // Result: C is 2

Commands are often more versatile and complex than operators and can sometimes be used to interact with the game in some way. For instance, the setPosATL command can be used to change the position of an object in the game world, the damage command returns the amount of damage an object has suffered and the systemChat command can be used to display a message in the system chat.

While operators are usually fairly intuitive to use, commands are often more complicated. As such, every single command (and every single operator) has a dedicated Community Wiki page documenting it. This makes the Community Wiki an essential resource for scripting as it can be consulted whenever an unfamiliar command is encountered or needs to be used. The documentation commonly includes information about the behaviour and effect of the command, its return value and the purpose and data types of its parameters.


Control Structures, Conditions and Booleans

Control Structures allow scripts to accomplish complex tasks. For instance, this code ...

if (damage player > 0.5) then { player setDamage 0; systemChat "The player has been healed."; } else { systemChat "The player is fine."; };

... behaves differently depending on the damage status of the player. The systemChat output and whether or not the player is healed changes dynamically based on how much health the player has when the code is executed.

Conditions

In the example above, the condition is damage player > 0.5. Like all conditions, it results in a Boolean value when evaluated:

  1. First, damage player is evaluated and returns a number.
  2. Then, the > operator compares that number to 0.5:
    • If the number is greater than 0.5, the > operator returns true.
    • If the number is less than or equal to 0.5, the > operator returns false.

Booleans

The data type Boolean only has two possible values: true and false.

Boolean Operations

There are three basic operations that can be performed on Boolean values:

Operation Description SQF Operator SQF Command
NOT (Negation) Inverts the input value. ! not
AND (Conjunction) Combines two Booleans into one. Only returns true if both input values are true. && and
OR (Disjunction) Combines two Booleans into one. Returns true if at least one of the input values is true. || or

Both the input and the output of these operations are Boolean values. Their behaviour is defined as follows:

NOT
Expression Result
!true false
!false true
AND
Expression Result
true && true true
true && false false
false && true false
false && false false
OR
Expression Result
true || true true
true || false true
false || true true
false || false false

Complex Conditions

Boolean operations can be used to create complex conditions by combining multiple conditions into one.

if ((alive VIP_1 && triggerActivated VIP_1_Task_Complete) || (alive VIP_2 && triggerActivated VIP_2_Task_Complete)) then { systemChat "At least one VIP has been rescued."; };

Beginners sometimes write conditions such as if (Condition == true) or if (Condition == false).

While doing so is not a real error, it is unnecessary because Control Structures (and Triggers) always implicitly compare the condition to true.

The correct (as in faster, more common and more readable) way to write such conditions is if (Condition) and if (!Condition) respectively.


Script Files

Scripts are usually placed in Script Files. It is of course possible and sometimes even necessary to use short pieces of code in the Editor (e.g. in the On Activation expression of a Trigger), but scripts can become long and complex, and then working with them is far easier when they are properly placed in script files. Additionally, some features are only accessible through the use of script files (Event Scripts for example).

Script files are basically just text files with a certain filename extension. For script files, that file extension is .sqf (or .sqs), but in the broader context of Arma scripting, modification, configuration and mission design, more file extensions can be encountered: .ext, .hpp, .cpp and .cfg to mention the most common ones.

File Creation

Unfortunately, Windows does not make the creation of blank files with a desired file extension easily accessible.

For instance, a common pitfall when trying to use Description.ext (a file that is used to configure certain mission features such as the respawn settings) for the first time is (unknowingly) creating Description.ext.txt instead of Description.ext because the Windows File Explorer hides file extensions by default. Obviously, Description.ext.txt will not work and will not have any of the desired effects on the mission because the game does not recognize it as Description.ext, but identifying a wrong file extension as the root cause of an issue when troubleshooting is notoriously difficult as one is usually looking for errors in the code and not in the filename.

While there are many different ways to create a blank text file with a specific file extension, the easiest method using native Windows tools is probably this:

  • Preparation (only needs to be done once):
  1. Open the File Explorer
  2. Open the View tab at the top
  3. Tick the File name extensions checkbox
  • File Creation:
  1. Navigate to the location where you want to create a new script file
  2. Right-click
  3. Go to New
  4. Click on Text Document
  5. Rename New Text Document.txt to what you need

File Locations

In the context of mission creation, script files generally need to be placed in the corresponding scenario folder (often also called the mission root folder). Every mission has its own scenario folder, it is created by the Editor when saving the scenario for the first time. By default it only contains a single file called mission.sqm; this file mostly stores data regarding Editor-placed entities and does not need to be touched when scripting.

Description.ext and Event Scripts have to be placed directly in the root of the scenario folder (i.e. next to mission.sqm), but all other files can be placed in subfolders of the scenario folder. A well-structured scenario folder could look like this:

Apex%20Protocol.Tanoa/
├── functions/
│   ├── fn_myFirstFunction.sqf
│   └── fn_mySecondFunction.sqf
├── scripts/
│   ├── myFirstScript.sqf
│   └── mySecondScript.sqf
├── description.ext
├── initPlayerLocal.sqf
├── initServer.sqf
└── mission.sqm

Each scenario folder is stored in either the missions or the mpmissions subfolder of the folder containing the Arma Profile that was used to create the scenario. For instance, the path to the scenario folder from the example above could be:

C:\Users\Scott Miller\Documents\Arma 3 - Other Profiles\Keystone\missions\Apex%20Protocol.Tanoa

The Editor uses percent-encoding for scenario folder names, that is why whitespaces in the scenario name are replaced with %20.

The Eden Editor provides a useful shortcut to quickly open a mission's scenario folder in the Windows File Explorer: With the mission open in the Editor, go to Scenario in the top left and then click on Open Scenario Folder.

See Also:

Editing Script Files

Because script files are essentially plain text files, they can be edited with just about any text editor. For instance, the native Windows Notepad can be used, but working with it is not very comfortable. As such, regular scripters typically use more versatile applications such as Notepad++ or Visual Studio Code, usually in combination with plugins that add additional support for SQF. One feature commonly provided by these plugins is syntax highlighting, and for good reason: Syntax highlighting makes code significantly more readable and helps recognizing and avoiding basic syntax errors. Consequently, it is highly recommended to use syntax highlighting.

See Community Tools - Code Edition for a selection of community-made applications and plugins for Arma Scripting.

Script Execution

The execVM command is used to execute script files.

For instance, myFirstScript.sqf from the File Locations example above can simply be executed like so:

execVM "scripts\myFirstScript.sqf";

This can be done anywhere: Within another script, from the Debug Console, in the On Activation or On Deactivation expression of a Trigger or in the init field of an Object in the Editor.



Miscellaneous

This section contains content from an old version of this page.


Before anything

Is your idea necessary?
Will players even notice or use what you want to script? Just because you can does not mean you should. Sometimes less is more!
Is it possible to do this in the editor?
The Eden Editor is a powerful tool and with it alone one can achieve a lot of things without writing a single line of code.
Poorly written scripts are a frequent cause of poor performance, both in singleplayer and multiplayer scenarios.
Can it be scripted using SQF?
This question might be hard to answer. Try to get as much information about what you want to do and what commands and functions there are before spending time on writing a script, just to find out that what you hoped to achieve is not possible after all.
Scripting is not the solution for everything!


Terms

The following is a collection of terms frequently encountered when talking or reading about scripting.

Game Engine
The core program of the game which executes your scripting commands at run time.
Script / Script File
Scripts are usually placed in script files. Script files contain code.
Syntax
See SQF Syntax (Arma, Arma 2, Arma 3).
See SQS Syntax (Operation Flashpoint, Arma).
Variables
A Variable is a named storage container for data.
The name of a variable is called its Identifier.
Data Types
The Data Type of a variable specifies which kind of data that variable can contain.
Operators
See Operators
Control Structures
See Control Structures
Functions
See Function


Must-read articles

Best Practices

See Code Best Practices

Debugging

Optimisation


Useful Links

These pages cover further aspects of scripting:

Consider the following resources for more general learning: