Skip to content

15 — Event scripts: the language

Index

The language of the event scripts that drive missions and campaigns: where the files live, their structure, variables, operators, sets, control flow, blocks, triggers, how events combine and what they carry. The events, actions and functions themselves are in chapters 16 and 17, the standard libraries, patterns and a full example in 18.

Contents

  1. Notation
  2. Where event scripts live
  3. File structure: FOR switches, USE, errors at loading
  4. Lexical rules
  5. Variables: scope, type auto-conversion
  6. Operators
  7. Sets
  8. Control flow: IF / ELSE, WHILE, FOREACH, BREAK, RETURN and INDEX
  9. Blocks
  10. Triggers: the ON statement: when a script runs, when values are read
  11. Event combination: precedence, conditions among events, ON EACH with combinations
  12. Event parameters: unit_parm, race_parm, race_or_region_parm, region_parm, missile_type_parm, AGGRESSOR
  13. Event embedded variables
  14. Action expressions

Notation

Notation Meaning
KEYWORD A language keyword. Keywords are case-insensitive; ON, on and On are the same.
italic_name Something you supply: an expression, a name, a parameter.
[ ... ] Optional part.
( a|b ) Choose exactly one of the alternatives.
[ ... ]+ Optional part that can be repeated.
ON [EACH] list_of_events [ACTION] action      // the form
on each TICK +SECONDS(10) CheckCasualties()   // written out

Where event scripts live

Events are declared per faction in the map (world) file. The EVENTS keyword can hold the script inline, but it is better practice to keep it in a separate file with Events FromFile:

Player "North America" Color "1188FF" Name "Blue" Portrait Index 15 Achievement ACH_AMERICAN_PSYCHO
    ModelPrefix "NA"
    Events FromFile "Maps/EarthRRUltraV3.Virtual/Events/North America.txt"

The "North America" faction runs the script in that file. That file can pull in other files with USE (see File structure). Each faction has its own script, with its own variables and triggers. Scripts of factions that have surrendered keep running; a faction not in play runs its script only with ExecuteEventsForNonActive. Scripts run on the server, and in multiplayer on the host.

Conventions used by the shipped campaigns:

  • One folder per mission, e.g. Scenario/DLC_3/DLC_3-6/EVENTS/, with one file per faction named after the faction (India.txt, Pakistan.txt).
  • Code shared by several factions of one mission goes in a common file in the same folder (India_Pakistan_Common.txt, EnemyCommon.txt).
  • Code shared by a whole campaign goes in Scenario/<Campaign>/Common/Common.txt. General-purpose libraries go in Scenario/LIB/ (Common.txt, Invasion.txt, Invasion_ext.txt, Invasion_ext_1.txt).
  • Paths are relative to the game's data root and are case-insensitive. Events and EVENTS both work.

File structure

An event script file has these parts, in this order:

  1. Global variable declarations. They always come first: def int Phase = 1.
  2. USE includes and block declarations, in any order: USE "Scenario/LIB/Invasion.txt", BLOCK Name(params) ... END.
  3. The main script body. This is a series of statements, triggers and actions, and it runs when the game starts.
  4. END, which finishes the whole script. Anything after it is never read.
def int PrimaryTimer = MINUTES(5)           // 1. globals first
def int CasualtiesMessageShown = false

USE "Scenario/DLC_3/Common/Common.txt"      // 2. includes and blocks

BLOCK StartPhase2()
  StdMessage(7528)
  throw "Allow AI" globally
END

FOR AI                                       // 3. main script body
  SUSPEND AI
  ON "Phase 2" StartPhase2()
FOR PLAYER
  StdMessage(7527)
  ON TICK +PrimaryTimer CheckForFinalSuccess()
FOR BOTH
  ON "Global War" GlobalWarMessage()
END                                          // 4. end of the script

FOR AI / FOR PLAYER / FOR BOTH switches

FOR AI, FOR PLAYER and FOR BOTH are switches, not blocks. They don't have their own END. A switch marks the statements that follow as relevant only when the faction is played by the AI (FOR AI), only when it is played by a human (FOR PLAYER), or in both cases (FOR BOTH).

  • Until the first switch, statements are FOR AI. Start the main body with a switch, as every shipped script does; otherwise it does nothing for a human player.
  • A switch works in the main body only. The body of a block, IF, WHILE or FOREACH runs for whoever its calling statement runs for, and a switch inside it has no effect. A trigger in the main body under FOR PLAYER calls its block for a human player only, and so on.
  • Global variable declarations apply to both. A DEF with a computed value in the main body gets its value only under a matching switch.
  • A switch is read as part of the statement before it when that statement can end in FOR: Suspend AI, Resume AI, AutoAttack, Execute, Unit … Make Visible, Enable / Disable Missiles, Ceasefire With, Peace Treaty With. SUSPEND AI followed by FOR PLAYER stops the loading with the undefined variable PLAYER. Put another statement in between, or use Dummy.
  • Because END finishes the whole script, don't write FOR AI … END followed by FOR PLAYER … END: the second part is never read. Put every switch inside one main body, as in the example above.
FOR AI
  SUSPEND AI
  Dummy                      // keeps FOR PLAYER from being read as part of SUSPEND AI
FOR PLAYER
  StdMessage(7527)
FOR BOTH
  on "Global War" GlobalWarMessage()
END

USE (includes)

USE "Scenario/LIB/Invasion.txt"

USE includes another file's contents in place. A USEd file may contain blocks and further USE statements only. The game stops reading it, with no error, at the first thing that is neither: a global variable there loses that declaration and every block after it. All included files share one namespace: every block from any file in the USE chain is visible everywhere, and so are the global variables of the main file. Two consequences:

  • A library may call blocks it doesn't define itself, as long as they were read before the call. For example, Invasion_ext.txt calls SimulateInvasion(), which is defined in Invasion.txt, so Invasion.txt must be USEd first. A call to a block not read yet stops the loading; a block can call itself. Only Execute "name" looks for its block when it runs, and so can reach one declared later.
  • A block name can be reused. A call written as a statement reaches the last declaration read, whichever file holds it. A call inside an expression reaches the last one read at that point of the file. For example, Main-9/US Pacific Allies.txt defines its own MoveGroup, replacing the one in LIB/Invasion.txt.

Errors at loading

A script is read when the map loads. These stop the loading:

  • a syntax error, or a variable or function that nothing defines;
  • a literal name the game data doesn't have: a unit type (ANY "X"), a missile type, a technology (Researched "X"), a faction, a region, a Geneva or AI category. Scripts that a game mode or a mod shares must name only what its data still has.

A city name that doesn't exist (Destroyed "Atlantis") is no error: the trigger never fires. A name given by an expression is looked up only when it is used: in an event, an unknown one matches nothing.

Execute for a block that the target faction's script doesn't have reports an error when it runs.

on Destroyed ANY "Army_Divison" CountLoss()   // misspelt unit type: the map doesn't load
on Destroyed "Atlantis" CountLoss()           // no such city: no error, never fires

Lexical rules

Item Rule
Case Keywords, built-in names, block names and variable names are all case-insensitive. SelfID, SELFID and selfid are the same name. Constants inside expressions are the exception: true, false, otGoto, Ground and the like must be written exactly so.
Comments // to end of line (also ///) and /* block comment */.
Strings "double quoted". A string can't span lines and there is no escape for ".
Numbers 42, 3.5
Booleans true, false (the same as 1 and 0)
Coordinates @(x, y): normalised map coordinates, both in 0.0 … 1.0. @(0.0, 0.0) is the map's top-left corner, @(1.0, 1.0) its bottom-right. Example: @(0.741866, 0.329272)
Sets {1, 2, 3}, {"Delhi", "Jaipur"}, {CITY("Lahore"), CITY("Lhasa")}
Layout Free-form. Line breaks and indentation are not significant, so a statement can span several lines and several statements can share a line. The examples put one statement per line only for readability. A ; between statements is accepted and ignored.
Indentation Not significant, but indent every body. Most real bugs are a missing END, and indentation makes them visible.

Variables

Variables are declared with DEF (or DEFINE) followed by the type, the name and, optionally, an initial value.

Type Holds
int integer
bool same as int (true = 1, false = 0)
float floating-point number
string text
coord a pair of floats: a map position
set a collection of values (see Sets)
unit a reference to an in-game unit or city
def int     int_var = 0
def int     NorthAmerica_ID = FACTION_ID("North America")
def float   float_var = 1.0
def string  string_var = "some str 2"
def coord   Coord_var = @(0.318653, 0.323283)
def set     Int_Set_Var = {0, 1, 2, 3}
def set     Coord_Set_Var = {@(0.318653, 0.323283), @(0.318653, 0.323283)}
def set     Set_Set_Var = {{0, 1, 2, 3}, {2, 3, 4, 5}}
def unit    unit_var = CITY("Moscow")
def set     Empty_Set               // no initial value = empty set / 0 / ""

Scope

  • Global variables are declared at the top of the main file, before any USE or BLOCK. They are visible in every block and in the main body of the whole USE chain, and they keep their value for the whole game.
  • A DEF in the main script body also keeps its value for the whole game, but only the main body after it can see it, not the blocks.
  • Local variables are declared inside a BLOCK or any nested body (IF, WHILE, FOREACH). A DEF inside a loop body runs on every iteration and re-initialises the variable. A local stays alive as long as a trigger that uses it is waiting.
  • Block parameters, typed FOREACH loop variables (ForEach unit U in …) and embedded event variables are local too.
  • A custom declaration overrides a built-in variable of the same name (SelfID, PlayerID, Index, Selected, Destination, …) in its scope. This is allowed but not good practice. For example, def int Index = 0 inside a loop hides the automatic loop counter.
def int Phase = 1                 // global: every block sees it

BLOCK CountArmies()
  def set Armies                  // local to the block
  select units OWNER==SelfID AND PRINCIPAL_TYPE=="Army_Division" into Armies
  Message "Phase " + Phase + ": " + SIZE_OF(Armies) + " armies"
END

Type auto-conversion

A value of one type can be assigned to a variable of another type. It is also converted automatically when passed as a parameter or mixed into an arithmetic expression.

From ↓ / To → int float coord string unit set
int – value @(v, 0) number as text unit with this UID, or 0 one-element set
float truncated – @(v, 0) number as text unit with this UID, or 0 one-element set
coord vector length √(x²+y²) vector length – "(x, y)" closest unit, missile or city within 1 km (slow: mind performance) one-element set
string numeric value, else 0 numeric value, else 0 first two numbers found – city of this name, else unit with this UID, else 0 one-element set
unit unit UID unit UID unit position, or @(0,0) if none UID as text – one-element set, or empty set if unit is 0
set set size set size first element as coord, or @(0,0) if empty "{e1, e2, …}" first element as unit, or 0 if empty copy with every element converted

When a value is used as an event parameter the rules differ slightly. For example, a unit converted to string gives the unit type name. See Event parameters.

Conversions the shipped scripts rely on all the time:

if (SomeSet)                       // true when the set is not empty (set -> int = size)
def coord pt = SomeUnit            // unit -> its position
def unit Base = GetBase(StartFrom) // a set returned by a block -> its first element
ForEach unit ThisCity in {"Jaipur", "Delhi"}   // city names -> city units

NOTE: When two different types meet in one arithmetic expression, the left operand decides the type of the result. The only exception is int mixed with float, which always gives float.

Operators

Kind Operators Notes
Arithmetic + - * / %, unary - *, /, % before +, -. + also concatenates strings ("Stop Airstrikes " + SelfID) and sets. An int divided by an int is an int; dividing by zero gives 0.
Comparison == != < > <= >= Always == to compare. A single = is assignment. Strings compare with exact letter case; units with == and != only.
Logical AND OR NOT Case-insensitive (and, or, not work). They exist only in conditions (IF, WHILE, SELECT, ON), not in values: x = a AND b is an error.
Membership x IN set, x IN* set IN* is the "relaxed" check: case-insensitive for strings, tolerant for floats and coords. If x is a set, the test asks for all its elements.
Assignment = += -= *= /= %= See the set and string notes below.
Increment x++ x-- Used as statements: Counter++.
  • For sets, -= deletes one matching element and /= deletes all matching elements. *= and %= aren't defined for sets.
  • For strings, only = and += are defined.
  • Precedence: NOT binds tightest, then AND, then OR, all grouping from left to right, in conditions, SELECT expressions and event combinations alike. a == 1 AND b == 2 OR c means (a == 1 AND b == 2) OR c, and NOT x IN S AND y means (NOT x IN S) AND y. Parentheses still make mixed expressions easier to read: NOT (Check IN RegionsToCheck).
Total = (Casualties * 2 + Losses) / 3
if (REGION_OWNER(RegName) != SelfID AND NOT (RegName IN Ignored))
  Ignored += RegName
end

Sets

Sets are used everywhere in ICBM scripts. A set is a collection of elements of one type: units, strings, coords, other sets and so on. The set itself has no type: its first element defines it, and later elements are converted to that type. Duplicates are allowed. Elements keep insertion order, so GET_FIRST, GET_LAST and "add to the beginning" are meaningful, but a set isn't sorted.

Access sets sequentially with FOREACH. Random access with GET_ELEMENT is slow on large sets.

Operation Effect
S = {"x", "y", "z"} initialise
S += "q" append one element
S = "q" + S prepend one element
S += {"q", "r", "s"} append another set
S = {"q", "r", "s"} + S prepend another set
S -= "x" delete one occurrence of "x"
S -= {"x", "y"} delete one occurrence of each
S /= "x" delete all occurrences of "x"
S /= {"x", "y"} delete all occurrences of each
"value" IN S exact membership test
"value" IN* S relaxed membership test (case-insensitive, float tolerance)
Clear S empty the set (an action)

Built-in set functions: SIZE_OF, IS_EMPTY, GET_ELEMENT, GET_FIRST, GET_LAST, DELETE_ELEMENT, DELETE_FIRST, DELETE_LAST, SHUFFLE, REMOVE_DUPLICATES, INTERSECTION, UNION, XOR. The most common source of sets is the SELECT action.

NOTE: A set converts to int as its size, so IF (set_name) … is the same as IF (SIZE_OF(set_name) != 0) …. Never write SIZE_OF(S) < 0: it is always false.

Control flow

These statements can be used inside any block or the main script body. Each body ends with END.

IF / ELSE

if (Casualties > 300000)
  throw "Nukes 200"
  if (Casualties > 600000)
    throw "Global War"
  end
else
  if (Casualties > 100000)
    throw "100K death"
  end
end
  • There is no ELSE IF. Nest a new IF inside the ELSE branch, and give it its own END.
  • Parentheses around the condition are optional (if MISSION_STATE("Missiles")==m_InProgress works), but always write them.

WHILE

def int i = 0
while (i < Number)
  Result += CREATE_UNIT("Army_Division", GET_ELEMENT(Points, i))
  i++
end

FOREACH

ForEach [type] variable_name IN set_expression ... END

ForEach unit ThisAirport in AllAirports
  unit HeadSAM follow ThisAirport
end
  • With a type (ForEach unit C in …), ForEach declares a new local variable that exists only inside the loop, and converts each element to that type: ForEach unit C in {"Delhi"} gives city units.
  • Without a type (ForEach C in …), nothing is declared: C must be a variable that already exists (declared with DEF, a block parameter, or a global). Writing ForEach NewVar in Set with an undeclared NewVar is an error.
  • The loop walks the set as it was when the loop started: changing the set inside the body doesn't change the iterations.

BREAK, RETURN and INDEX

  • break leaves the innermost WHILE or FOREACH.
  • return expression leaves a block and returns a value. The block should declare a return type (see Blocks). The value is mandatory: to leave a block that returns nothing, write return 0.
  • INDEX is an automatic, loop-local counter that starts at 0 and increases on each iteration of the innermost loop. It isn't defined outside loops. It's handy to walk a parallel set, and while (index < 4) repeats a body 4 times without a counter:
ForEach int ID in Commands
  if (ThisID == ID)
    Mission GET_ELEMENT(CommandsMission, Index) SUCCESS
    break
  end
end

Blocks

Blocks are sub-programs, like functions. Each has a name, optional parameters, a body and an optional return value.

BLOCK [return_type] block_name [(type name [, type name]+)]
  ...body...
END
BLOCK int GetFactionCasualties(int ID)
  return STAT("INITIAL_POPULATION", ID) - STAT("POPULATION", ID)
END

BLOCK SpawnSpecOps(coord StartFrom, coord LandTo)
  def unit Base = GetBase(StartFrom)
  if (Base)
    SendSpecOpsFromBase(Base, LandTo)
  end
END
  • block_name can be an identifier or a quoted string (BLOCK "Global War"). Names are case-insensitive and shared across all USEd files.
  • Separate parameters with commas. The game also reads a list without them (BLOCK CheckForGlobalWar(string MType int WRace)), but write the commas (pitfalls checklist).
  • A block name can be reused, in the same file or across the USE chain; see USE. This is normal, not a bug.
  • Parentheses are optional when there are no parameters.
  • A block holds at most 128 parameters and local variables together. A call passes at most 32 arguments.
  • A body (block, IF, WHILE, FOREACH) ends with END. The first branch of an IF ends with ELSE, and the ELSE branch ends with END.
  • ref before a parameter type passes by reference: the block works on the caller's variable under a new name. Without ref, a copy is made. If a value rather than a variable is passed to a ref parameter, it silently becomes by-value, so it's safe to declare large set parameters as ref set for speed and still pass constant sets.
  • Return type: declare it (BLOCK int …, BLOCK unit …, BLOCK bool …) when the block uses return value. A block with a return type should return on every path.
  • Call a block with exactly the declared number of arguments. The game doesn't check it: with too few, the block's parameters and local variables read wrong values, and extra arguments are dropped.
  • A block can call itself, directly or through an ON trigger. This is the standard way to build repeating behaviour (see Common patterns).

Triggers: the ON statement

The main script body and block bodies are mostly made of triggers. A trigger runs an action when an event happens.

ON [EACH] list_of_events [ACTION] action
    [DELETE WHEN list_of_events]
  • Without EACH, the trigger fires once and is removed. With EACH, it fires every time the events happen.
  • The optional DELETE WHEN removes the trigger, without running the action, when its events happen. Use it to cancel repeating triggers.
  • The action is one action. To do several things, call a block.
  • An action written without ON runs immediately, as if its event had already happened.
  • ON statements inside a block register their triggers when the block runs. They outlive the block. A block that re-arms itself is the standard repeating-timer pattern.
  • The keyword ACTION between the events and the action is optional and does nothing.
on each TICK +SECONDS(10) CheckCasualties()
  delete when "Global War"

BLOCK StartAirstrikes()
  ...
  on TICK +SECONDS(20) StartAirstrikes()
     delete when "Stop Airstrikes " + SelfID
END

The list of events can be a single event or a combination of several (see Event combination). Each event can expose values through embedded variables.

When a script runs

Every faction's script is processed once per tick. The events that happened are delivered as they happen, and a timer event is delivered to every script each tick. A trigger whose events are complete runs its action at that tick's pass, in the order of the statements. Statements that don't wait for an event run as soon as the pass reaches them, so the main body's plain statements run at the start of the game.

FOR AI
  StdMessage(7527)                    // runs at the start of the game
  on TICK +SECONDS(10) StdMessage(7528)   // runs 10 seconds later
END

When values are read

In a trigger's events and DELETE WHEN:

  • Local variables and block parameters are read once, when the ON statement is reached. on destroyed Group Foo() waits for the units Group held at that moment, even if the set changes later.
  • Global variables and function calls are read every time the event arrives. on destroyed AllTargets Foo() with a global AllTargets follows the set as it changes.

Actions freeze local variables the same way, including the arguments of a block call. The text of a Message, the name in a Throw and the conditions of While and Select read them when they run.

Event combination

Events in one trigger can be combined:

Form Fires when
NOT Event the event hasn't happened so far; see below
Event OR Event either event happens
Event AND Event both events have happened, in any order
Event THEN Event both have happened, in this order

An event that has happened stays counted: the trigger remembers it until the whole combination is complete.

NOT is true until its event happens, and false from then on. It is tested whenever any event reaches the trigger, every tick at least. Its place is in an AND, for what must not have happened by the time the rest is complete:

on TICK +MINUTES(10) AND NOT "Convoy arrived" throw "Convoy late" globally
on "Convoy left" THEN (TICK +MINUTES(10) AND NOT "Convoy arrived") throw "Convoy late" globally

The first waits ten minutes and fires unless "Convoy arrived" came before that. The second counts both the ten minutes and the arrival from "Convoy left".

  • Once its event has happened, the AND can't complete: the trigger stays waiting and does nothing. To remove it, use DELETE WHEN.
  • Write NOT last. A finished part of a combination stays counted, and a NOT inside it with it: NOT "X" AND "A" AND "B" reads (NOT "X" AND "A") AND "B" and stops watching "X" when "A" happens. "A" AND "B" AND NOT "X" watches it until both have happened.
  • Without an AND, a NOT completes on the first event that reaches the trigger and isn't its own. on NOT "X" … runs within a tick, NOT "X" OR "Y" too, and in NOT "X" THEN "Y" the left part is done after a tick. ON EACH NOT "X" runs on every event until "X" happens.
  • A condition counts as an event here: NOT (Counter > 3) is false for good once Counter > 3 was true at a test, even if the value drops again.
on destroyed any "Army_Base" or (destroyed any "Tactical_Airbase" then destroyed any "Tactical_Airbase") throw "Phase 2" globally
on Region_Occupied TargetRegion by ALLY PLUS ME THEN TICK +SECONDS(20) AutoInvade(TargetRegion)
on TICK +SECONDS(30) OR "Restart Airstrike" StartAirstrikes()

Precedence

From tightest to loosest: NOT, then AND, then OR, then THEN. Operators of the same level group from left to right.

  • NOT applies to the next event only: NOT "X" AND "Y" means (NOT "X") AND "Y". Write NOT ("X" AND "Y") to negate both.
  • THEN binds loosest, because its left part must have triggered before its right part is even checked. A relative TICK +n on the right of THEN starts counting only then. The event that completes the left part can't also count for the right part: A THEN A needs two A.
  • An AND right after the first faction of War_Started, Ceasefire and Alliance_Formed belongs to the event: War_Started FOR ME AND "Phase 2" reads "Phase 2" as a faction. Write (War_Started FOR ME) AND "Phase 2".
Written Means
A AND B OR C (A AND B) OR C
A OR B THEN C (A OR B) THEN C
A OR B THEN C AND D THEN E OR NOT F ((A OR B) THEN (C AND D)) THEN (E OR (NOT F))
on (destroyed any "Army_Base") or (destroyed any "Airport") or (Region_Invaded ANY of ME) THEN TICK +SECONDS(30) throw "Phase 2" globally

Here any of the three events starts the 30-second timer. Parentheses around mixed operators are still recommended, for readability.

The same precedence applies to AND, OR and NOT in IF and WHILE conditions and in SELECT expressions.

Conditions among events

A comparison or an IN test can stand among the events, in parentheses:

on "Spawn" AND (Counter > 3) StartPhase2()
  • It is tested whenever any event reaches the trigger, every tick at least. Once true it stays true.
  • A trigger made of conditions only is tested once when the statement is reached, and then removed whatever the result. It is an IF: use IF.
  • Only a comparison or IN counts as a condition. Any other value (on MissionOK("A") …) is read as the name of a custom event.
  • Don't write condition THEN condition: use AND.

ON EACH with combinations

With EACH a fresh copy of the trigger starts waiting as soon as this one has moved on:

  • ON EACH A OR B: fires on every A and every B.
  • ON EACH A THEN B: every A opens a wait of its own. on each "Arrived" then TICK +SECONDS(5) Check() runs Check once for each arrival, 5 seconds after it.
  • ON EACH A AND B: the next round starts only when both have happened.

Event parameters

The events in chapter 16 and many actions take these parameter forms. Where a form names a faction relative to "us", "us" is the faction whose script runs.

unit_parm

Describes a unit or group of units.

Form Meaning
ANYTHING any unit
ANY "unit_type" any unit of the type (including its High and Low states). Cities are ANY "VirtualCity" or ANY {City}
ALL "unit_type" the same as ANY "unit_type"
ANY {class [, class]} any unit of the classes: Ground, Naval, Subwater, Airborne, Missile, HighMissile, SubwaterMissile, Satellite, City, AbstractPosition
ANY expression any unit of the type(s) given by the expression: a string holding a unit type, or a set of such strings. Example: destroyed ANY BaseTypes, where BaseTypes = {"Army_Base", "Tactical_Airbase"}
AGGRESSOR in an action: the aggressor unit
"City name" a specific city
expression an int, unit or set expression (including block calls): a unit UID, a unit, or a set of them

As an embedded variable it holds the specific unit (type unit). Converted to int it gives the unit UID, to string the unit type name ("VirtualCity" for a city), and to coord the unit position.

on Destroyed ANY "Army_Base" CountLoss()
on each Damaged ANY {Ground, Naval} ->(unit U) Retreat(U)
on Destroyed Commands CheckCommands()      // a set of units in a variable

race_parm

Describes one or more factions.

Form Meaning
ANYONE any faction
ANYONE ELSE any faction except ours
ANYONE BUT PERMANENT ALLY not us and not any of our permanent allies
ANYONE BUT ALLY not us and not any of our allies
PERMANENT ALLY (also PERMANENT ALLIES) our faction or one of our permanent allies. A permanent alliance is the higher tier of alliance: unlike a usual alliance, it can't be broken.
ALLY (also ALLIES) one of our allies, not our own faction
ALLY PLUS ME our faction or any of our allies
ENEMY any faction at war with us
ENEMY PLUS NEUTRAL any enemy or neutral faction
NEUTRAL any neutral faction
AGGRESSOR in an action: the aggressor faction
ME / SELF our faction (the one running the script)
"Faction name" a specific faction
expression int (faction ID), string (faction name), or a set of them

"Our faction" means the faction the script runs for. As an embedded variable it holds the faction ID (int). Converted to string it gives the faction name.

on War_Started BETWEEN ME AND ANYONE BUT ALLY StartAttacks()
on Exploded NUKE BY ENEMY PLUS NEUTRAL throw "Nuclear war" globally

race_or_region_parm

Form Meaning
REGION "region name" a specific region
REGION string_expression a region given by an expression
race_parm any race_parm form above. A literal string may also name a region; a faction of that name goes first

As an embedded variable it holds the ID (int) or name (string) of the faction that owns the place, also when the trigger asks for a region.

on Exploded NUKE IN REGION "North Japan" BY ANYONE throw "North Japan hit" globally
on Exploded NUKE IN ME throw "We are hit" globally

region_parm

Form Meaning
ANY / ANYTHING any region
"region name" a specific region
expression a string expression, or a set of region names, including block calls: Region_Invaded {"West India", "South India"}

As an embedded variable it holds the region ID (int). Converted to string it gives the region name.

on Region_Invaded {"West India", "South India"} BY ENEMY DefendSouth()

missile_type_parm

Form Meaning
ANYTHING any missile type
NUKE (also NUCLEAR) has an explosion of the Nuclear type
BIO (also BIOLOGICAL) has an explosion of the Biological type
CHEM (also CHEMICAL) has an explosion of the Chemical type
EMP has an explosion of the EMP type
MASS DESTRUCTION (also MASS) has an explosion with the TriggerResponse property
SPECIAL Bio, Chem or EMP
CONVENTIONAL has an explosion of the Conventional type
ANY {class [, class]+} a combination of the classes above: a missile of any of them. A single class can be written without braces: ANY NUKE. ANY "missile type" is an error
GENEVA CATEGORY "name" any missile in that Geneva category. Short form: GENEVA "name" (e.g. by geneva "Chemical"). The name must be a literal string
AI_CATEGORY "name" any missile in that AI category; a literal string too
"missile type" an explicit missile type
expression a string, or a set of strings, including block calls

As an embedded variable it holds the missile ID (int or string). Converted to coord it gives the explosion position. Converted to unit it gives the parent (launching) unit.

BEST is not a missile type. It is only valid in the Unit … Attack action, as BY BEST.

on Launched NUKE throw "Nukes launched" globally
on Exploded ANY {CHEM, BIO} IN ME throw "Inhumane weapons" globally
on Destroyed ANY "Army_Base" BY "250kt_MRBM" CountMissileHit()

AGGRESSOR

AGGRESSOR is for actions: it names what set off the trigger. In an event parameter it matches nothing.

The trigger's event Aggressor unit Aggressor faction
Attacked, Damaged, Destroyed, Destroyed INACTIVE, Destroyed … OF, Exploded the attacker its owner
Launched, Launched Hosted the launcher its owner
Boarded the host its owner
Visible the unit seen its owner
Besieged, Occupied, Deoccupied, Orders Completed, Inactive, Deployed the unit itself its owner
Researched, Tech_Available, Queued_Tech, Queued_Unit, Queued_Missile none the other faction, if not ours

Other events leave it empty. The plain statements of a block called by the trigger inherit it; triggers inside that block get their own.

on each Attacked ANY "Army_Base" AttackUnit AGGRESSOR
on Attacked ANY "Airport" Declare War AGGRESSOR

Event embedded variables

Events are often general, like ON REGION_INVADED ANY OF ME DoSomething(), but you usually need to know which region or unit triggered them. Put an embedded variable after any event parameter:

ON event event_parameter ->(type variable_name) ...

The type is int, bool, float, coord, string or unit; set stops the game when the trigger fires. The variable is local to the trigger's action. To fill the same variable from two events of one trigger, declare it once and repeat only its name: ->(unit U) here, ->(U) there. Declaring the name twice is an error.

Examples:

ON REGION_INVADED ANY ->(string RegionName) OF ME DoSomething(RegionName)
ON REGION_INVADED ANY ->(int RegionID) OF ME DoSomething(RegionID)
on each destroyed Commands ->(int ThisID) CheckCommandsDestroyed(ThisID)
ON each exploded nuke ->(string MType) by anyone ->(int WRace) CheckForGlobalWar(MType, WRace)

Custom events can carry up to two extra values with PARM:

throw "CheckAttackedCity" PARM ThisCity PARM NumKilled globally
...
ON "CheckAttackedCity" ->(unit City) ->(int Killed) HandleCity(City, Killed)

A value that wasn't supplied reads as -1 in an int or float, as empty in a string, as no unit in a unit, and as @(0, 0) in a coord. The word ANYTHING is accepted after the event name and before each ->, and has no effect.

In saved games the game writes triggers with a few more words: EMBEDDED before ON (the embedded variables declared in advance), ORIGINAL after a statement (the fresh copy of an ON EACH), triggered, checked_not_triggered and aggressor (the trigger's state). They are not for hand-written scripts.

Action expressions

These are the value types that actions accept.

  • unit_expression: an int (unit UID) or unit value, or a set of them.
  • unit_type_expression: a string naming a unit type, or a set of such strings.
  • coordinates_expression: a coord, or a set of coords. Units and city names convert to their positions automatically.
  • mission_name_expression: a string naming a mission defined in the map.
  • unit_type_or_missile_type_expression: a unit-type or missile-type string, or a set of them.
unit Fleet move {@(0.80, 0.40), @(0.82, 0.38)}     // unit_expression, coordinates_expression
Build {"Army_Division", "250kt_MRBM"} x 2           // unit_type_or_missile_type_expression
Mission "Airports" add 1                            // mission_name_expression