Skip to content

17 — Event scripts: SELECT, variables and functions

Index · The language · Events and actions · Libraries and patterns

Finding units with SELECT, the built-in variables and every built-in function. The language around them is in chapter 15.

Contents

  1. SELECT
  2. SELECT variables
  3. SELECT functions
  4. SELECT TECHS
  5. Built-in variables
  6. Constants
  7. Built-in functions
  8. Maths and time
  9. Units: identity
  10. Units: state
  11. Units: ranges and combat
  12. Units: groups, creation and removal
  13. Hosting
  14. Weapons
  15. Factions and relations
  16. Diplomatic offers
  17. Technology
  18. Regions and territory
  19. Map points
  20. Missions
  21. Sets
  22. Bit operations
  23. UI and highlights

SELECT

Syntax:

Select (CITIES | UNITS [INACTIVE] | CITIES UNITS [INACTIVE] | UNITS [INACTIVE] CITIES) select_expression
       [ORDER BY expression [DESCENDING | ASCENDING] [THEN expression [DESCENDING | ASCENDING]]+]
       INTO set

SELECT tests every unit and/or city in the game against select_expression and puts the ones that match into set, replacing what the set held. The select_expression is a boolean expression in which the SELECT variables and SELECT functions take their values from the unit being tested. For example, OWNER==SelfID AND OCCUPATION_RANGE > 10 is true for all our armies and for nothing else.

select units OWNER==SelfID AND TYPE in {"Airport", "Tactical_Airbase"} AND false==HAS_ORDER(otAttack) into Airbases
select cities REGION==RegionName order by POPULATION DESCENDING into AllCities
select units inactive OWNER==SelfID AND PRINCIPAL_TYPE in {"Army_Division", "Army_Base"} into AllArmies
  • CITIES (also CITY) tests cities, UNITS tests units; at least one of them is required. UNITS INACTIVE also includes hosted (inactive) units, at any depth. Cities in destroyed regions are skipped.
  • Sort keys can be any expression, and the SELECT variables and functions work in them: ORDER BY POPULATION DESC, ORDER BY DISTANCE(Start), ORDER BY REGION THEN HEALTH DESC. Numbers compare by value, strings alphabetically; ties come in no particular order. DESC and ASC are short forms; without either, the order is ascending. SORT BY and SORTING BY are synonyms of ORDER BY, and the word BY may be left out.
  • Always write INTO and a variable. The word INTO itself can be left out, because the first word after the expression is taken as the result variable. If the variable is forgotten too, that first word is the start of the next statement. See Pitfalls.
  • Ordinary variables, block parameters and functions can be used in the expression as well: DISTANCE(Start) < 50, REGION in CheckRegions.
  • Inside the expression the SELECT names win. A variable or parameter of yours named Region, Type or Owner can't be read there: REGION==Region compares the unit's region with itself. The SELECT functions replace the ordinary functions of the same name in the same way, so HAS_HOSTED(This, "Attack") inside a SELECT is the one-unit form with This as the type and gives a wrong result. Copy such a value to a differently named variable before the SELECT.
  • The SELECT variables and the SELECT-only functions exist only inside a SELECT.
  • The layout is free-form, so a long expression can span several lines.
  • SELECT scans every unit, so it's expensive. Don't run it every tick on large maps; a 5–30 second TICK is typical.

SELECT variables

Inside a SELECT expression these names stand for a property of the unit being tested. The last column links to the built-in function that reads the same property of any unit.

Variable Type Meaning Function
ID int The unit's UID.
OWNER int The faction ID of the unit's owner. OWNER
TYPE string The unit type, for example "Army_Division", "Army_Mobile_Mode" or "Army_Entrenched". Each state of a multi-state unit is a different type; to match all states, use PRINCIPAL_TYPE. TYPE
PRINCIPAL_TYPE string The type of the unit's principal state, the same for all its states: "Army_Division" for "Army_Division", "Army_Mobile_Mode" and "Army_Entrenched". PRINCIPAL_TYPE
CLASS int The unit class, one of the constants Ground, Naval, Subwater, Airborne, Missile, HighMissile, SubwaterMissile, Satellite, City, AbstractPosition. CLASS
NAME string The name assigned to the unit. NAME
OCCUPATION_RANGE float, km The unit's occupation radius. OCCUPATION_RANGE > 10 is a common test for "is an army". OCCUPATION_RANGE
SPEED float, km/h The unit's speed. SPEED
RANGE float, km The unit's maximum range. RANGE
SAFE_RANGE float, km The maximum range that still lets the unit return safely to its airbase, carrier and so on. SAFE_RANGE
WEAPON set of strings All missile types in the unit's current config, including those with a count of 0. GET_WEAPON
AVAILABLE_WEAPON set of strings The missile types in the current config whose count is greater than 0 and which the owner may use. GET_AVAILABLE_WEAPON
WEAPON_CONFIG string The equipped weapon config, or "none". GET_WEAPON_CONFIG
POSITION coord The unit's true position.
ALTITUDE float The unit's height above the ground. ELEVATION
DESTINATION coord The unit's destination: DISTANCE(DESTINATION, This)<OCCUPATION_RANGE. DESTINATION
VISIBLE set of faction IDs The factions the unit is visible to: SelfID IN VISIBLE. VISIBLE_FOR
GHOSTVISIBLE set of faction IDs The factions the unit's ghost is visible to. GHOSTVISIBLE_FOR
REGION string The name of the region where the unit is, or "no region". REGION
REGION_ID int The ID of the region where the unit is, or -1. REGION_ID
TERRITORY int The faction ID that owns the territory at the unit's position. TERRITORY
LAND_SEGMENT int The land or water segment ID at the unit's position. LAND_SEGMENT
POPULATION int The current population of the city; 0 for other units. POPULATION
ORIGINAL_POPULATION int The population of the city at game start; 0 for other units. ORIGINAL_POPULATION
POPULATION_PERCENT float, 0–100 The current population as a percentage of the initial population; 0 for other units. POPULATION_PERCENT
HEALTH float The unit's current HP. HEALTH
HEALTH_PERCENT float, 0–100 The unit's HP as a percentage of full HP. HEALTH_PERCENT
GROUP int The unit's follow group ID (not the selection group). If the unit follows nobody, this is its own UID; otherwise it is the leader's UID: Select units GROUP==Group(Leader) INTO FoundShips. GROUP
HOST unit The parent unit, for example the airbase of a bomber. HOST
PRINCIPAL_HOST unit The topmost parent in the hierarchy, for example the army base holding a transport plane that holds an army. PRINCIPAL_HOST
OCCUPIED set of faction IDs The enemy factions whose units occupy this unit or city. OCCUPIED_BY
SIEGED set of faction IDs The enemy factions whose units besiege this unit or city. SIEGED_BY
IS_ACTIVE int 1 if the unit is alive and not carried inside another unit. IS_ACTIVE
HANGAR_SIZE int The full size of the unit's hangar, 0 if it has none. The function HANGAR_SIZE on a unit gives the free space instead.
HANGAR_SPACE_AVAILABLE int The space currently free in the unit's hangar. HANGAR_SIZE
HANGAR_SPACE_REQUIRED int The hangar space this unit occupies. HANGAR_SPACE_REQUIRED
select units OWNER==SelfID AND PRINCIPAL_TYPE=="Army_Division" AND HEALTH_PERCENT < 50 into Damaged
select cities OWNER==SelfID AND SelfID IN VISIBLE ORDER BY POPULATION DESC into Known

SELECT functions

Inside a SELECT expression these take the tested unit as an implicit first argument, so each has one parameter fewer than the built-in function it links to, whose entry describes the arguments. CAN_BE_ATTACKED_BY, ENEMY, ALLY and PERMANENT_ALLY exist only here.

"Factions" here means a faction name, faction ID, unit (its owner), coord (the territory owner), or a set of them. A name or ID that doesn't exist makes the test 0.

Form inside SELECT Returns Built-in function
VISIBLE_FOR([factions]) 1 if the tested unit is fully visible to any of the factions, otherwise 0. Without an argument, the visibility bitscale. VISIBLE_FOR
GHOSTVISIBLE_FOR([factions]) The same for the unit's ghost. GHOSTVISIBLE_FOR
HAS_WEAPON(missile_type [, count]) 1 if the missile type is in the unit's config; if count is non-zero, the number of missiles remaining. HAS_WEAPON
AFFECTED_BY(explosion_type) The ticks the unit will stay affected by a lasting explosion type, 0 if not affected. AFFECTED_BY
ATTACK_RANGE([target]) float: the maximum attack range against a unit or unit type, or against anything. ATTACK_RANGE
CAN_ATTACK(target [, without_hosted [, surfaced [, in_range]]]) 1 if the tested unit can attack the target in its current state. CAN_ATTACK
CAN_BE_ATTACKED_BY(attacker [, without_hosted [, surfaced [, in_range]]]) 1 if attacker, a unit or a unit type, can attack the tested unit: the reverse of CAN_ATTACK. With a unit type, surfaced and in_range have no effect.
RADAR_RANGE([target [, faction_id]]) float: the tested unit's detection range against a unit, or a unit type optionally followed by the faction ID of its owner. Without an argument, the maximum. RADAR_RANGE
HAS_ORDER([order_type [, target]]) 1 if the tested unit has an order, one of this type, or one of this type against this unit: false==HAS_ORDER(otAttack). HAS_ORDER
DISTANCE(x [, y]) float, km. With one argument, the distance from the tested unit to x: a unit, a UID, a city name, a coord, or a set of them, which gives the minimum. With two arguments, the distance from x to y; the tested unit isn't used. DISTANCE
MAX_DISTANCE(x [, y]) As DISTANCE, but the maximum when a set is involved. MAX_DISTANCE
MAX_HOSTED(unit_type [, recursive]) The maximum number of units of that type the tested unit can host. MAX_HOSTED
NUM_FIT_IN_HANGAR(hosted_type) How many more units of hosted_type fit into the tested unit's hangar now. NUM_FIT_IN_HANGAR
HAS_HOSTED(unit_type [, recursive]) The number of hosted units of that type. HAS_HOSTED
HAS_LAUNCHED_HOSTED(unit_type) The number of the tested unit's hosted units of that type that are out of the host. HAS_LAUNCHED_HOSTED
OCCUPIED_BY(factions) 1 if the tested unit or city is occupied by any of the factions. OCCUPIED_BY
SIEGED_BY(factions) 1 if the tested unit or city is besieged by any of the factions. SIEGED_BY
ENEMY(factions) 1 if the tested unit's owner is at war with any of the factions: select units ENEMY(SelfID) AND CLASS==Ground into Targets.
ALLY(factions) 1 if the tested unit's owner is allied with any of the factions.
PERMANENT_ALLY(factions) 1 if the tested unit's owner is a permanent ally of any of the factions.
select units ENEMY(SelfID) AND CLASS==Ground AND DISTANCE(Capital) < 300 into Threats
select units OWNER==SelfID AND CAN_ATTACK(Target) AND false==HAS_ORDER(otAttack) into Idle

SELECT TECHS

SELECT TECHS (also TECHNOLOGIES) is accepted, and always gives an empty set. It can't be combined with UNITS or CITIES. To list technologies, use GET_FACTION_TECHS.

def set MyTechs = GET_FACTION_TECHS(SelfID)   // not SELECT TECHS, which gives an empty set

Built-in variables

A custom declaration with the same name overrides a built-in variable in its scope. This is allowed, but not good practice.

SELFID

Type: int

The faction ID of the faction the script runs for.

if (OWNER(This)==SelfID)

SELFNAME

Type: string

The name of the faction the script runs for.

Message "Orders for " + SelfName

PLAYERID

Type: int

The faction ID of the human player's faction, or -1 if there is none.

BlockHomelandAttack PlayerID

PLAYERNAME

Type: string

The name of the human player's faction, or "error" if there is none.

Message PlayerName + " has crossed the border"

CURRENT_TICK

Type: int

The current game tick. TIME events are absolute ticks on the same scale.

if (CURRENT_TICK > MINUTES(20))

POLLUTION

Type: float, 0.0–100.0

The current global pollution percentage.

if (POLLUTION > 50.0)
  throw "Nuclear Winter" globally
end

ADVISOR_PORTRAIT

Type: string

The path of the advisor portrait image. Used with Message.

Message UI_STRING(7328) Position TopLeft Portrait ADVISOR_PORTRAIT

SCENARIO_TOTAL_SCORE

Type: int

All "stars" earned in all previous scenarios of the campaign.

if (SCENARIO_TOTAL_SCORE >= 20)
  GRANT_TECH(SelfID, "Tactical_nukes")
end

INDEX

Type: int

An automatic, always-local counter of the innermost loop. It starts at 0 and increases on each iteration. It isn't defined outside loops. See Control flow.

ForEach unit U in Group
  if (Index == 0)
    unit U move Destination
  end
end

CURSOR

Type: coord

The map position under the mouse cursor of the local player. It differs between computers, so use it only for single-player testing and tutorials, never for game logic in multiplayer.

Message "Cursor: " + CURSOR      // for testing only

SELECTED

Type: unit

The unit currently selected by the local player, or none. Like CURSOR, it is local to each computer.

Message "Selected: " + TYPE(SELECTED)

Constants

In an expression these need their exact case, unlike the rest of the language: true works and TRUE is an unknown name. The mission states are the exception, and so is a unit class inside ANY {…} in an event parameter.

  • Unit classes: Ground, Naval, Subwater, Airborne, Missile, HighMissile, SubwaterMissile, Satellite, City, AbstractPosition. Compare them with CLASS.
  • Order types: otGoto, otAttack, otFollow, otLaunchAircraft, otStateUp, otStateDown, otTraverse, otDisassemble, otPatrolPoint, otLaunchAircraftModDestination, otWait, otBoard, otChangeAttackState, otSelfDestruct, and otNone (no order). Used with HAS_ORDER and GET_ORDER.
  • Mission states: m_InProgress (0), m_Success (1), m_Fail (2). Returned by MISSION_STATE.
  • E1_UNDEFINED: equals -1. Used to skip an optional argument: GET_VICINITY_POINTS(pt, 3, E1_UNDEFINED, REGION_ID(City)).
  • AI point types: listed under AI_POINT.
  • true / false: 1 and 0.
if (otNone==GET_ORDER(Sub) AND CLASS(Sub)==Subwater)

Built-in functions

Parameters in [ ] are optional. Many parameters accept several types, and the type changes what the function does, so each entry lists the accepted types. "Faction" means a faction ID (int) or faction name (string) unless stated otherwise; "unit" means a unit value, and often also a unit UID (int) or a city name (string), which convert automatically.

Quick index

Maths and time

RAND

Syntax: RAND() · RAND(x) · RAND(a, b [, c]+)
Returns: a random value; what kind depends on the arguments.

  • No argument: an integer from 0 to 232 − 1.
  • One set argument: a random element of the set: def string ToDefend = RAND(MyRegions).
  • One other argument: an integer from 0 to x − 1, so RAND(SIZE_OF(S)) is a valid index into S. RAND(1) is always 0.
  • Several arguments: one of the arguments, chosen at random.
def coord Point = GET_ELEMENT(RandomPoints, RAND(SIZE_OF(RandomPoints)))
on each tick +SECONDS(60 + RAND(30)) SendAirborneTroopsFromBase(Base, CITY("Busan"))

MIN / MAX

Syntax: MIN(a [, b]+) · MAX(a [, b]+)
Returns: the smallest or largest value.

  • Several arguments: the smallest or largest of them. Any comparable type works (int, float, string…).
  • One set argument: the smallest or largest element of the set.
  • One other argument: its value.
def int PlanesToAdd = MIN(5, MAX_HOSTED(This, "Attack") - HAS_HOSTED(This, "Attack"))

LERP

Syntax: LERP(a, b, k)
Returns: the linear interpolation between a and b with coefficient k.

  • a, b: float or coord.
  • k: the coefficient.
def coord Midway = LERP(@(0.55, 0.21), @(0.60, 0.22), 0.5)

SECONDS / MINUTES / HOURS

Syntax: SECONDS(n) · MINUTES(n) · HOURS(n)
Returns: int: the number of game ticks in n seconds, minutes or hours of game time: 60, 3600 and 216000 ticks per unit. n is read as a whole number, so MINUTES(1.5) is one minute; write SECONDS(90).

on each TICK +SECONDS(10) CheckCasualties()
MISSION "Mission Timer" TIMER MINUTES(30)

Units: identity

UNIT

Syntax: UNIT(x)
Returns: a unit value, or none.

  • x: a unit UID (int) or a city name (string).
def unit VladivostokBase = UNIT(444560)

CITY

Syntax: CITY(name)
Returns: the city as a unit value, or none.

  • name: city name (string), or the name the city was renamed to.

Store cities as units ({CITY("Kiev"), CITY("Minsk")}) rather than names: every later use of a name needs a costly string-to-unit conversion.

def unit Capital = CITY("Moscow")

TYPE

Syntax: TYPE(unit)
Returns: string, the unit type, such as "Army_Mobile_Mode", or "not found". SELECT variable: TYPE.

if (TYPE(This)=="Landing_Ship")

PRINCIPAL_TYPE

Syntax: PRINCIPAL_TYPE(x)
Returns: string, the principal type: the same for every state of a multi-state unit, such as "Army_Division".

  • x: a specific unit, or a unit type (string).
if (PRINCIPAL_TYPE(U)=="Army_Division")    // also "Army_Mobile_Mode" and "Army_Entrenched"

CLASS

Syntax: CLASS(x)
Returns: int, one of Ground, Naval, Subwater, Airborne, Missile, HighMissile, SubwaterMissile, Satellite, City, AbstractPosition.

  • x: a specific unit, or a unit type (string).
if (CLASS(ThisUnit)==Ground AND "Nepal"==REGION(ThisUnit))

NAME

Syntax: NAME(unit)
Returns: string, the unit's or city's own name. If no own name is set, the name of its defining technology. "not found" if the unit doesn't exist.

Message NAME(ThisCity) + " " + UI_STRING(6961) Position TopLeft

SET_NAME

Syntax: SET_NAME(unit, name)
Returns: int: 1, or 0 if the unit isn't found.

Sets the unit's own name.

  • unit: unit.
  • name: string. An empty string clears the own name.
SET_NAME(VIP, UI_STRING(6710))

ID_NAME

Syntax: ID_NAME(unit)
Returns: string: the id_name of a city, or the defining technology of a unit.

This is not the unit type. Use TYPE for that.

MISSION ID_NAME(ThisCity) SUCCESS      // a mission named after the city's id_name

OWNER

Syntax: OWNER(x)
Returns: int, a faction ID.

  • x a unit, a UID, or a city name (string): the owner of the unit or city.
  • x a coord: the owner of the territory at that point.
if (OWNER(This)==SelfID)
if (OWNER(@(0.558, 0.209))==PlayerID)     // the territory at a point

Units: state

HEALTH

Syntax: HEALTH(unit)
Returns: float, the unit's current HP. Returns 0 if the unit is dead or not found, so HEALTH(x) > 0 is the usual "still alive" test.

if (HEALTH(Check)<=0)

HEALTH_PERCENT

Syntax: HEALTH_PERCENT(unit)
Returns: float, HP as a percentage of full HP (0–100). 0 if the unit is dead or not found.

if (HEALTH_PERCENT(Flagship) < 50)
  throw "Flagship damaged" globally
end

IS_ACTIVE

Syntax: IS_ACTIVE(unit)
Returns: int: 1 if the unit is alive and not carried inside another unit.

if (IS_ACTIVE(ThisSpyPlane))

POPULATION

Syntax: POPULATION(city)
Returns: int, the city's current population.

  • city: unit, or city name (string).
def int Casualties = ORIGINAL_POPULATION(ThisCity) - POPULATION(ThisCity)

ORIGINAL_POPULATION

Syntax: ORIGINAL_POPULATION(city)
Returns: int, the city's population at game start. city as in POPULATION.

if (ORIGINAL_POPULATION(HK) - POPULATION(HK) > 500000)

POPULATION_PERCENT

Syntax: POPULATION_PERCENT(city)
Returns: float, the remaining population as a percentage (0–100). city as in POPULATION.

if (POPULATION_PERCENT(HK)<=70.0)

ELEVATION

Syntax: ELEVATION(x)
Returns: float, height above the ground. SELECT variable: ALTITUDE.

  • x: unit, or city name (string).
Message "Altitude: " + ELEVATION(SELECTED)

DESTINATION

Syntax: DESTINATION(unit)
Returns: coord, where the unit is going.

  • If the unit has a follow order: the final destination of the unit it follows.
  • If it has no move order: its current position.
  • If it isn't found: @(-1, -1).
if (DISTANCE(DESTINATION(Leader), Destination)>10)
  unit Leader move Destination
end

GET_X / GET_Y

Syntax: GET_X(x) · GET_Y(x)
Returns: float, the X or Y map coordinate.

  • x a unit, unit UID (int) or city name (string): that unit's coordinate.
  • Otherwise x is treated as a coord.
def float NorthOfDaNang = GET_Y("Da Nang")
if (GET_X(SuggestedPoint) > 0)        // a point was found

GET_ORDER

Syntax: GET_ORDER(unit)
Returns: int, the type of the unit's current order (otGoto, otAttack, …, see HAS_ORDER), or otNone if it has no order or isn't found.

if (otNone==GET_ORDER(Sub))

HAS_ORDER

Syntax: HAS_ORDER(unit [, order_type [, target]])
Returns: 1 if the unit has an order, otherwise 0.

  • unit: the unit to check.
  • order_type: optional; checks one order type (int): otGoto, otAttack, otFollow, otLaunchAircraft, otStateUp, otStateDown, otTraverse, otDisassemble, otPatrolPoint, otLaunchAircraftModDestination, otWait, otBoard, otChangeAttackState, otSelfDestruct.
  • target: optional; a unit. Checks for an order against that target: HAS_ORDER(ThisUnit, otAttack, Target).

SELECT form: see SELECT functions.

if (false==HAS_ORDER(ThisUnit, otAttack, Target))
  unit ThisUnit attack Target
end

AFFECTED_BY

Syntax: AFFECTED_BY(x, explosion_type)
Returns: int, the ticks left under a lasting explosion effect (0 if not affected).

  • x: unit, or city name (string).
  • explosion_type: string.
if (AFFECTED_BY(Radar, "EMP_Blast") > 0)

VISIBLE_FOR

Syntax: VISIBLE_FOR(unit [, factions])
Returns: depends on the arguments.

  • One argument: the visibility bitscale (bit n set if visible to faction ID n).
  • With factions: 1 if the unit is visible to any of them, otherwise 0. factions is a faction ID (int), name (string), or a set of IDs or names.

SELECT form: see SELECT functions.

if (VISIBLE_FOR(Convoy, PlayerID))

GHOSTVISIBLE_FOR

Syntax: GHOSTVISIBLE_FOR(unit [, factions])
Returns: as VISIBLE_FOR, for the unit's ghost. A visible unit also counts as ghost-visible.

if (false==GHOSTVISIBLE_FOR(Convoy, PlayerID))

GET_KILLED_BY

Syntax: GET_KILLED_BY(unit)
Returns: unit, the unit that destroyed unit, or none.

def unit KilledBy = GET_KILLED_BY(ThisCenter)

Units: ranges and combat

OCCUPATION_RANGE

Syntax: OCCUPATION_RANGE(x)
Returns: float, the occupation radius in km.

  • x: a specific unit, or a unit type (string).
def float Radius = OCCUPATION_RANGE("Army_Division")

SPEED

Syntax: SPEED(x)
Returns: float, the speed in km/h. x as in OCCUPATION_RANGE.

def float Hours = DISTANCE(Leader, Destination) / SPEED(Leader)

RANGE

Syntax: RANGE(x [, faction])
Returns: float, the travel range in km.

  • x: a specific unit, or a unit type (string).
  • faction: optional; calculate for a unit type owned by another faction (technologies can change ranges). Default: SelfID.
if (DISTANCE(Base, Target) < RANGE("Bomber"))

SAFE_RANGE

Syntax: SAFE_RANGE(x [, faction])
Returns: float, the safe travel range: the maximum range that still allows a safe return to the airbase, carrier and so on. Arguments as in RANGE.

def int MaxRange = SAFE_RANGE("Spec_Ops_Helicopter")

ATTACK_RANGE

Syntax: ATTACK_RANGE(x [, target [, faction]])
Returns: float, the attack range in km.

  • x: a specific unit, or a unit type (string).
  • target: optional; a specific unit, or a unit type (string). Returns the maximum attack range against it. Without it, the maximum attack range overall.
  • faction: optional, only when x is a unit type; as in RANGE.
if (ATTACK_RANGE(This, ThisCity)>DISTANCE(This, ThisCity))
def int AttackRange = ATTACK_RANGE("SSBN_Surfaced", "VirtualCity")

CAN_ATTACK

Syntax: CAN_ATTACK(x [, target [, without_hosted [, surfaced [, in_range]]]])
Returns: 1 if x can attack target in its current state.

  • x: a specific unit, or a unit type (string; then the faction running the script is assumed as owner, and only target is used).
  • target: a specific unit, or a unit type (string). Without it: 1 if x can attack anything at all.
  • without_hosted: if non-zero, attacks by hosted units don't count. Default: 0, they count.
  • surfaced: if non-zero, force the check in the surfaced state.
  • in_range: if non-zero, also require the target to be within firing range (then target must be a specific unit).

SELECT form: see SELECT functions.

if (CAN_ATTACK(ThisSub, ThisCity, false, true, true))

RADAR_RANGE

Syntax: RADAR_RANGE(x [, target [, faction]])
Returns: float, the detection range.

  • x a unit or unit type (string): target can be another unit, or a unit type (string) optionally followed by a faction ID. Without target, the maximum detection range.
  • x a radar type (string): target as above. Without target, the raw detection range.
if (RADAR_RANGE(Check, "Cyber_Warfare_Center", SelfID) > DISTANCE(Check, Pt))

DISTANCE / MAX_DISTANCE

Syntax: DISTANCE(a, b) · MAX_DISTANCE(a, b)
Returns: float, the distance in km.

  • a: a unit, a unit UID, a coord, or a city name (string).
  • b: the same, or a set of them. DISTANCE then returns the minimum distance and MAX_DISTANCE the maximum.

SELECT form: see SELECT functions.

if (DISTANCE(DESTINATION(Leader), Destination)>10)
def float Nearest = DISTANCE(This, FrontCities)       // the nearest city of the set

Units: groups, creation and removal

GROUP

Syntax: GROUP(unit)
Returns: int, the follow group ID (not the selection group): the unit's own UID if it follows nobody, otherwise the leader's UID.

def int GroupID = GROUP(Leader)
Select units GROUP==GroupID INTO FoundShips

SELECTION_GROUP

Syntax: SELECTION_GROUP(group_number [, faction_id])
Returns: set, the units of a player-defined selection group (the groups set with Ctrl+number). Empty if the group doesn't exist.

  • faction_id: optional; whose group. Default: the human player's faction.
def set FirstGroup = SELECTION_GROUP(1)

GROUP_LEADER

Syntax: GROUP_LEADER(units)
Returns: unit, the leader of the follow group of the first unit in units, or 0 if that unit isn't in a follow group.

  • units: a set of units, or a single unit.
def unit Leader = GROUP_LEADER(Fleet)
if (Leader)
  unit Leader move Destination
end

MAKE_GROUP

Syntax: MAKE_GROUP(set)
Returns: unit, the group leader, or 0 if the set holds no active unit.

Makes the active units of the set one follow group. If they already all follow one leader, the group is left as it is. Otherwise the first active unit of the set becomes the leader, its follow orders are deleted, and every other unit is ordered to follow it. Check the result against 0 before using it.

def unit Leader = MAKE_GROUP(FullGroup)

GET_BLOCKERS

Syntax: GET_BLOCKERS(city)
Returns: set, the active units blocking the city or unit: those holding it, friendly or not. Test their owners to tell defenders from attackers.

def int Friendly = 0
def set Blockers = GET_BLOCKERS(City)
ForEach unit B in Blockers
  if (ALLIES(OWNER(B), OWNER(City)))
    Friendly++
  end
end

CREATE_UNIT

Syntax: CREATE_UNIT(type, where [, config_or_name [, name]])
Returns: int, the UID of the new unit, which converts to a unit wherever one is expected; 0 if the type doesn't exist.

Instantly creates and deploys a unit. It belongs to the faction running the script, or, when it is created hosted, to the host's owner. Creating it doesn't throw Deployed.

  • type: unit type (string).
  • where:
  • a unit (or unit UID) that can host the new one: the new unit is created hosted, and inactive;
  • a unit that can't host it: the new unit is placed at that unit's position;
  • a coord: the placement position.
  • config_or_name: optional; the starting weapon config. If no config with that name exists, it is used as the unit's name.
  • name: optional; the unit's name. Without one, the unit takes a free name from its type's name bank, if the language files have one (12 §5).

New units have their AI switched on. Suspend it (SUSPEND AI FOR …) if the script moves them.

CREATE_UNIT("Army_Division", Base)          // hosted in Base
Result+=CREATE_UNIT("Army_Division", Point) // placed at Point

CREATE_GROUP

Syntax: CREATE_GROUP(types, where [, names])
Returns: int, the UID of the first created unit, which is the group leader.

Instantly creates and deploys a group of units following the leader.

  • types: a set of unit types (string).
  • where: a coord, or a unit whose position is used for the leader.
  • names: optional; a set of unit names, in the order of types. A single string instead is the weapon config of the leader, as in CREATE_UNIT.

New units have their AI on, as with CREATE_UNIT.

def int Leader = CREATE_GROUP({"Cruiser", "Destroyer", "Destroyer"}, SpawnPoint)

TRANSFER_UNIT

Syntax: TRANSFER_UNIT(faction, units)
Returns: int, the number of units actually transferred.

  • faction: the receiving faction.
  • units: a unit or a set of units.

The transfer kills each unit and creates a new one, so old unit values and UIDs become invalid, and the new units have their AI on. Hosted units are transferred with their host. The receiving faction must be active; units it already owns are skipped. Each transfer throws Occupied.

TRANSFER_UNIT(SelfID, AllSilos)

KILL

Syntax: KILL(units)
Returns: int, the number of units killed.

Kills the units immediately. Cities are never killed. The normal Destroyed events are thrown.

  • units: a unit or UID, or a set of them.
if (KILL(VIP)>0)

Hosting

HANGAR_SIZE

Syntax: HANGAR_SIZE(x)
Returns: int.

  • x a specific unit: the currently available space in its hangar.
  • x a unit type (string): the maximum hangar space of that type.
if (HANGAR_SIZE(TYPE(This))>0)   // can this kind of unit carry anything?

The SELECT variable HANGAR_SIZE is the full size; HANGAR_SPACE_AVAILABLE is the free space.

HANGAR_SPACE_REQUIRED

Syntax: HANGAR_SPACE_REQUIRED(x)
Returns: int, the hangar space x occupies.

  • x: a unit, a unit type (string), or a set of units or of unit types: the total for all of them.
if (HANGAR_SPACE_REQUIRED(Group) <= HANGAR_SIZE(Transport))

NUM_FIT_IN_HANGAR

Syntax: NUM_FIT_IN_HANGAR(unit, hosted_type)
Returns: int, how many units of hosted_type fit into the hangar: into the free space for a unit, into the empty hangar for a unit type. 0 if hosted_type isn't carried in that hangar.

  • unit: a unit, UID or city name, or a unit type.
  • hosted_type: a unit type (string), or a unit (its type).
def int TotalToAdd = NUM_FIT_IN_HANGAR(This, "Army_Division")

MAX_HOSTED

Syntax: MAX_HOSTED(unit, hosted_type [, recursive])
Returns: int, the maximum number of units of that type the unit can host.

  • unit: a unit, UID or city name, or a unit type.
  • hosted_type: string; "" means all types. So does a name that isn't a unit type, so a misspelt type counts everything.
  • recursive: if non-zero, also search inside hosted units.
while (TotalTransports<MAX_HOSTED(Base, TransportUT))

HAS_HOSTED

Syntax: HAS_HOSTED(unit, hosted_type [, recursive])
Returns: int, the number of hosted units of that type. unit is a unit, UID or city name; the other arguments are as in MAX_HOSTED.

def int TotalArmiesHosted = HAS_HOSTED(Base, "Army_Division", true)

HAS_LAUNCHED_HOSTED

Syntax: HAS_LAUNCHED_HOSTED(unit, hosted_type)
Returns: int, the number of units of hosted_type launched from unit that are currently out of it. "", or a name that isn't a unit type, counts every type.

Add it to HAS_HOSTED to count every aircraft that belongs to a base, including those currently flying:

HAS_HOSTED(This, "Fighter") + HAS_LAUNCHED_HOSTED(This, "Fighter")

GET_HOSTED

Syntax: GET_HOSTED(unit)
Returns: set, all units hosted by unit.

def set AllHosted = GET_HOSTED(This)

GET_LAUNCHED_HOSTED

Syntax: GET_LAUNCHED_HOSTED(unit)
Returns: set, the units launched from unit that are currently out of it.

def set InFlight = GET_LAUNCHED_HOSTED(Carrier)

HOST

Syntax: HOST(unit)
Returns: unit, the parent unit, for example the airbase of a bomber.

def unit MyHost = HOST(ThisSpyPlane)

PRINCIPAL_HOST

Syntax: PRINCIPAL_HOST(unit)
Returns: unit, the topmost parent in the hierarchy.

def unit Base = PRINCIPAL_HOST(ThisArmy)

Weapons

GET_WEAPON_CONFIG

Syntax: GET_WEAPON_CONFIG(unit)
Returns: string, the name of the currently selected weapon config, "none" if it has none, "not found" if the unit doesn't exist.

  • unit: unit or UID.
if (GET_WEAPON_CONFIG(ThisBomber)=="none")

SET_WEAPON_CONFIG

Syntax: SET_WEAPON_CONFIG(unit, config [, force_refill])
Returns: int: 1, -1 if the unit has no such config, 0 if the unit isn't found.

Sets the weapon config.

  • unit: unit or UID.
  • config: config name (string).
  • force_refill: if non-zero, refill the unit even if the config's missiles aren't available or the territory doesn't allow refilling.
SET_WEAPON_CONFIG(NewTruck, "Light 100kt Bomb", true)

WEAPON_CONFIG_AVAILABLE

Syntax: WEAPON_CONFIG_AVAILABLE(x, config [, partly [, faction_id]])
Returns: 1 if the weapon config is available, otherwise 0.

  • x: a unit, or a unit type (string).
  • config: config name (string).
  • partly: if non-zero, also return 1 when only some of the config's weapons are available.
  • faction_id: whose technologies count. Default: the faction running the script.
if (WEAPON_CONFIG_AVAILABLE("Mobile_SRBM", "Nuclear"))

SET_HOSTED_CONFIG

Syntax: SET_HOSTED_CONFIG(unit, hosted_type, config)
Returns: int: 1, -1 if the hosted type has no such config, 0 if the unit or the hosted type isn't found.

Sets the weapon config of the units of hosted_type hosted by unit.

SET_HOSTED_CONFIG(Airbase, "Attack", "100kt Bomb")

HAS_WEAPON

Syntax: HAS_WEAPON(unit, missile_type [, count])
Returns: 1 if the missile type is in the unit's config. If count is non-zero, the number of missiles remaining instead.

  • missile_type: string.

SELECT form: see SELECT functions.

def int Left = HAS_WEAPON(ThisSub, "250kt_SLBM", true)

GET_WEAPON

Syntax: GET_WEAPON(unit [, recursive])
Returns: set, all missile IDs in the current config that the owner may use, including those with a count of 0.

  • recursive: if non-zero, also collect the weapons of carried units (not of units in a hangar), without duplicates.
AllPotentialWeapon += GET_WEAPON(This)

GET_AVAILABLE_WEAPON

Syntax: GET_AVAILABLE_WEAPON(unit [, recursive])
Returns: set, the missile IDs in the current config with a count greater than 0. recursive as in GET_WEAPON.

AllAvailableWeapon += GET_AVAILABLE_WEAPON(This, true)

GET_STORED_WEAPON

Syntax: GET_STORED_WEAPON(unit)
Returns: set, the missile IDs the unit has in stock, for units that can stock missiles.

AllAvailableWeapon += GET_STORED_WEAPON(This)

WEAPON_RANGE

Syntax: WEAPON_RANGE(missile_type [, unit_or_type [, target [, check_usable]]])
Returns: float, the range of a weapon; the raw value with only missile_type; -1 if the missile type doesn't exist.

  • missile_type: string.
  • unit_or_type: a specific unit, or a unit type (string), that carries the weapon.
  • target: a specific unit. Returns the real range against this target.
  • check_usable: only when unit_or_type is a specific unit. If non-zero, also check that the weapon can actually be used against the target.
def float MRBMRange = WEAPON_RANGE("250kt_MRBM")

WEAPON_YIELD

Syntax: WEAPON_YIELD(missile_type [, faction_id])
Returns: float, the yield in kilotons, or -1 if the missile type doesn't exist. Technologies can change it, so pass the faction for another faction.

if (WEAPON_YIELD(MType, WRace)>=250)

WEAPON_GENEVA_CATEGORY / WEAPON_AI_CATEGORY

Syntax: WEAPON_GENEVA_CATEGORY(missile_type) · WEAPON_AI_CATEGORY(missile_type)
Returns: set, all Geneva categories, or all AI categories, of the missile type.

if ("Chemical" IN WEAPON_GENEVA_CATEGORY(MType))

NUM_AVAILABLE

Syntax: NUM_AVAILABLE(type [, faction_id])
Returns: int, the number of missiles in stock, or of non-deployed units.

  • type: missile type or unit type (string).
  • faction_id: an int. Default: the faction running the script.
if (NUM_AVAILABLE("SRBM-N")<20)

ALL_AVAILABLE_MISSILES / ALL_AVAILABLE_UNITS

Syntax: ALL_AVAILABLE_MISSILES([faction_id]) · ALL_AVAILABLE_UNITS([faction_id])
Returns: set, all missile types in the stockpile, or all unit types available for deployment.

def set AllAvailableWeapon = ALL_AVAILABLE_MISSILES()
def set ReadyToDeploy = ALL_AVAILABLE_UNITS(PlayerID)

Factions and relations

FACTION_ID

Syntax: FACTION_ID(name)
Returns: int, the faction ID, or -1 if no faction has that name.

def int US_ID = FACTION_ID("United States")

FACTION_NAME

Syntax: FACTION_NAME(id)
Returns: string, the faction name, or "error" if the ID isn't valid.

Message FACTION_NAME(WRace) + " used nuclear weapons"

PORTRAIT

Syntax: PORTRAIT(faction)
Returns: string, the path of the faction's portrait image.

Message UI_STRING(7330) Position TopLeft Portrait PORTRAIT("China")

FACTION_ACTIVE

Syntax: FACTION_ACTIVE(faction [, include_surrendered])
Returns: 1 if the faction is active, otherwise 0. With a second argument of any type, it also returns 1 for a faction that was active but surrendered.

if (FACTION_ACTIVE("Pakistan"))

SURRENDERED

Syntax: SURRENDERED(faction)
Returns: 1 if the faction has surrendered.

if (SURRENDERED("Separatists"))

GET_FACTIONS

Syntax: GET_FACTIONS([include_surrendered])
Returns: set, the IDs of the active factions. With an argument of any type, factions that surrendered are included too.

def set AllFactions = GET_FACTIONS(true)      // also those that surrendered

FACTION_SCORE

Syntax: FACTION_SCORE(faction)
Returns: the faction's current score.

if (FACTION_SCORE(SelfID)>FACTION_SCORE("United States"))

STAT

Syntax: STAT(stat_name, faction_or_region)
Returns: int, a statistic. An unknown stat_name gives a meaningless number, so spell it exactly; case doesn't matter.

  • faction_or_region: a faction or region, by ID (int) or name (string).
  • stat_name, for a faction:
  • "POPULATION": current population, the sum over the regions it owns now;
  • "ORIGINAL_POPULATION": current population in its originally owned regions;
  • "PRODUCTION", "SCIENCE", "ESPIONAGE": current points;
  • "INITIAL_POPULATION": population at game start in the regions it owns now;
  • "INITIAL_ORIGINAL_POPULATION": population at game start in its originally owned regions;
  • "NUM_REGIONS": number of regions it owns now;
  • "GDP_POTENTIAL": the faction's GDP, not altered by losses;
  • "GDP_INITIAL": the same, as if it owned exactly its original regions.
  • stat_name, for a region: "REGION_PRODUCTION", "REGION_SCIENCE", "REGION_ESPIONAGE", "REGION_POPULATION" (current values), and "REGION_INITIAL_PRODUCTION", "REGION_INITIAL_SCIENCE", "REGION_INITIAL_ESPIONAGE", "REGION_INITIAL_POPULATION" (initial values).
return STAT("INITIAL_POPULATION", ID) - STAT("POPULATION", ID)   // casualties

ALLIES / PERMANENT_ALLIES / ENEMIES

Syntax: ALLIES(f [, g]) · PERMANENT_ALLIES(f [, g]) · ENEMIES(f [, g])
Returns:

  • One argument: the bitscale of f's allies, permanent allies or enemies. For ALLIES and PERMANENT_ALLIES it includes f itself. Test it with GET_BIT.
  • Two arguments: 1 if f and g are allies, permanent allies or enemies, otherwise 0.
if (ALLIES(SelfID, REGION_OWNER(TargetRegion)))

GET_ALLIES / GET_PERMANENT_ALLIES

Syntax: GET_ALLIES(faction) · GET_PERMANENT_ALLIES(faction)
Returns: set of faction IDs: the allies or permanent allies of faction. It always includes faction itself.

Declare War GET_ALLIES("United States")
def set Bloc = GET_PERMANENT_ALLIES(SelfID)

GET_ENEMIES

Syntax: GET_ENEMIES(faction)
Returns: set of the faction IDs at war with faction.

def set EnemyIDs = GET_ENEMIES(SelfID)

GET_RELATIONS

Syntax: GET_RELATIONS(f, g)
Returns: int: 0 at war, 1 neutral, 2 allies, 3 permanent allies.

if (GET_RELATIONS(SelfID, PlayerID)==0)     // at war

GET_ALLIANCE_POLICY

Syntax: GET_ALLIANCE_POLICY(faction_id, policy)
Returns: int: 1 if the alliance of the faction has the policy, otherwise 0. Also 0 for a faction outside an alliance.

  • policy, in any case: one of "CONSTRUCTION", "ESPIONAGE", "SCIENCE", "RADARDATA", "NUCLEARASSETS", "BUILDONTERRITORY", "MUTUALDEFENCE", "INSTANTRESEARCHSHARING".
if (GET_ALLIANCE_POLICY(SelfID, "MutualDefence"))

SET_ALLIANCE_POLICY

Syntax: SET_ALLIANCE_POLICY(faction_id, policy [, enable])
Returns: int: 1 if the policy was set, otherwise 0.

Forces the policy for the alliance of the faction. Pass 0 as the third argument to cancel it. policy as in GET_ALLIANCE_POLICY. A faction outside an alliance is left alone.

SET_ALLIANCE_POLICY(SelfID, "BuildOnTerritory")
SET_ALLIANCE_POLICY(SelfID, "BuildOnTerritory", false)

SET_STEPPED_INVASION

Syntax: SET_STEPPED_INVASION(on)
Returns: int, the new setting.

With a non-zero argument, the armies of an AI invasion that stand in their own, allied or neutral territory first move to a border crossing, or to a border defence point of the AI cache, and only then to their targets. It helps an AI that gets stuck on its way through a neutral faction with blocked borders. The setting holds for all factions until the end of the game. The map key UseIntermediatePointForInvasion sets the same thing.

SET_STEPPED_INVASION(true)

Diplomatic offers

Scripts can send the same offers the diplomacy screen and the AI send. The receiver answers as it answers any offer: a human player gets the offer pop-up, an AI faction decides for itself. See Items of an offer for what an offer can hold. No shipped campaign uses them.

CREATE_OFFER

Syntax: CREATE_OFFER(from, to [, requests [, offers]])
Returns: int, the ID the new offer will carry; 0 with fewer than two arguments.

Sends an offer from faction from to faction to.

  • from, to: a faction name or ID, a unit (its owner) or a coord (the territory owner).
  • requests: a set of items that from asks of to.
  • offers: a set of items that from gives to to.

Each item is itself a set of strings, the name first:

def int Deal = CREATE_OFFER(SelfID, PlayerID, {{"CeaseFire"}, {"Territory", "Poland"}}, {{"Hardware", "Cruiser", "2"}})

The offer enters the game a moment after the call, so test it with OFFER_EXISTS on a later tick, not in the same block.

OFFER_EXISTS

Syntax: OFFER_EXISTS(id)
Returns: int: 1 if an offer with this ID is waiting for its answer, otherwise 0.

BLOCK CheckDeal()                 // called a few seconds after CREATE_OFFER
  if (false==OFFER_EXISTS(Deal))
    throw "Deal answered"
  end
END

CREATE_COUNTER_OFFER

Syntax: CREATE_COUNTER_OFFER(id)
Returns: int, the ID the counter-offer will carry, or 0 if there is no such offer.

Rejects the offer and sends a new one with the sides swapped and the same items: what was asked is offered, what was offered is asked. Change it with ADD_REQUEST / ADD_OFFER.

def int Counter = CREATE_COUNTER_OFFER(Deal)

ADD_REQUEST / ADD_OFFER

Syntax: ADD_REQUEST(id, item [, value [, count]]) · ADD_OFFER(id, item [, value [, count]])
Returns: int: 0.

Adds one item to what a waiting offer asks for, or to what it gives. Here the item is written as plain arguments, and the value can be of its own type: ADD_REQUEST(Deal, "Hardware", "Cruiser", 2). The addition isn't sent to other computers, so use these two in single-player scripts only.

ADD_REQUEST(Counter, "Territory", "Poland")
ADD_OFFER(Counter, "Hardware", "Cruiser", 2)

Items of an offer

Item Value Meaning
"CeaseFire", "PeaceTreaty", "Partnership", "Alliance" The relation between the two sides.
"Intelligence" Intelligence data.
"WithdrawForces" The giver withdraws its forces.
"StopContributions" The giver stops taking the contributions the receiver pays it.
"CooperationAgreement" "Production", "Intelligence", "Research", "RadarData" or "NuclearAssets" A cooperation agreement of that kind.
"Territory" region The giver hands over the region.
"Technology" technology ID The giver hands over the technology.
"Hardware" unit type, then count (default 1) The giver hands over units.
"War" faction The giver declares war on the faction.
"StopSupport" faction The giver stops arming the faction.
"StopWar" faction The giver makes a ceasefire with the faction.
"KeepFighting" faction The giver promises to go on fighting the faction for 20 minutes.
"StopCovert" The giver promises no covert operations against the receiver for PromiseLength ticks (AI/CovertOps.txt). Valid only after the receiver destroyed a covert unit of the giver's, or to renew such a promise.
"SpareCivilians" The giver promises to spare civilians for SpareCiviliansLength ticks (AI/Infamy.txt): no strikes aimed at cities and no chemical or biological weapons, against anyone. Valid only in Conquest scoring, from a giver that has lately killed civilians on purpose, and not between allies.
"Sanction" faction The giver puts sanctions on the faction for 30 minutes. Valid only in Conquest scoring, on a third faction that is allied to neither side and that the giver doesn't sanction yet.
"LiftSanctions" The giver lifts its sanctions on the receiver. Valid only in Conquest scoring, while the giver sanctions the receiver.
"Contributions" percent A share of the giver's production, paid as contributions.
"Aid" percent A share of the giver's production, paid as aid, which the giver can stop at any time.

An item that can't be read (an unknown name, technology, region or unit type, or a missing value) is dropped without a message.

def int Deal = CREATE_OFFER(SelfID, PlayerID, {{"Sanction", "China"}}, {{"Technology", "Tactical_nukes"}})

DISABLE_OFFER_TYPE / ENABLE_OFFER_TYPE

Syntax: DISABLE_OFFER_TYPE(type) · ENABLE_OFFER_TYPE(type)
Returns: int: 0.

Forbids, or allows again, a kind of diplomacy item, for every faction.

DISABLE_OFFER_TYPE("Alliance")
on "Phase 2" ENABLE_OFFER_TYPE("Alliance")

Technology

GRANT_TECH

Syntax: GRANT_TECH(faction, techs)

Grants technologies to the faction. All their parents that aren't discovered yet are granted too. No Researched events are thrown for them.

  • techs: a technology ID (string), or a set of IDs. Unknown IDs are ignored.
GRANT_TECH(SelfID, "Chemical_Weapons")
GRANT_TECH(PlayerID, {"Tactical_nukes", "Chemical_Weapons"})

TECH_AVAILABLE

Syntax: TECH_AVAILABLE(faction, tech)
Returns: 1 if the technology is available to the faction, otherwise 0.

if (TECH_AVAILABLE(PlayerID, "Tactical_nukes"))

GET_FACTION_TECHS

Syntax: GET_FACTION_TECHS(faction [, include_zero_cost])
Returns: set, the technology IDs available to the faction; with faction -1, every technology. If the second argument is non-zero, zero-cost technologies are included.

def set AllPlayerTechs = GET_FACTION_TECHS("Soviet Union")

TECH_NAME

Syntax: TECH_NAME(tech)
Returns: string, the display name of the technology ID.

Message "New technology: " + TECH_NAME("Tactical_nukes")

GET_TECH_TYPE / GET_TECH_PARENTS / GET_TECH_LEADS_TO

Syntax: GET_TECH_TYPE(tech) · GET_TECH_PARENTS(tech) · GET_TECH_LEADS_TO(tech)
Returns: set of technology IDs: the technology's categories (its [TYPE] entries), its parents, or the technologies it leads to. Empty if tech isn't found.

def set TechTypes = GET_TECH_TYPE(Tech)
if (NOT "Weapons of Mass Destruction" in TechTypes)

Regions and territory

REGION

Syntax: REGION(x)
Returns: string, the name of the region.

  • x: a coord inside the region, a unit (the region it is in), or a city name (string).
def set AdjRegions = ADJACENT_REGIONS(REGION(ThisSpecOps))

REGION_ID

Syntax: REGION_ID(x)
Returns: int, a region ID, or -1 if there is none.

  • x a region name (string): the ID for that name.
  • x a unit or unit UID (int): the region where the unit is now.
def int MyRegion = REGION_ID(ThisSpecOps)

REGION_NAME

Syntax: REGION_NAME(x)
Returns: string, a region name, or "no region".

  • x: a region ID (int), a coord inside the region, a unit (its region), or a region name (string).
def string RegName = REGION_NAME(RegID)

REGION_OWNER

Syntax: REGION_OWNER(region)
Returns: int, the faction ID of the current owner, or -1 if there is no such region.

  • region: a region name (string), region ID (int), a coord inside it, or a unit (its region).
if (REGION_OWNER(RegName)!=SelfID)

REGION_ORIGINAL_OWNER

Syntax: REGION_ORIGINAL_OWNER(region)
Returns: int, the faction ID of the original owner, or -1. region as in REGION_OWNER.

if (REGION_ORIGINAL_OWNER(RegID)==USSR_ID)

REGION_CITIES

Syntax: REGION_CITIES(region)
Returns: set of the cities in the region, as unit values. region as in REGION_OWNER.

def set Targets = REGION_CITIES("South Korea")

ADJACENT_REGIONS

Syntax: ADJACENT_REGIONS(region [, owners])
Returns: set of the names of the neighbouring regions.

  • region: as in REGION_OWNER.
  • owners: optional; a faction, or a set of factions. Only neighbours owned by them are returned. With -1, only neighbours owned by no faction.
def set MyRegions = ADJACENT_REGIONS(RegionName, SelfID)
if (ADJACENT_REGIONS(RegName, EnemyIDs))   // borders an enemy?

FACTION_REGIONS

Syntax: FACTION_REGIONS(factions [, as_ids])
Returns: set of the regions of the faction(s): names, or IDs if as_ids is non-zero.

  • factions: a faction, or a set of factions. With -1, the regions owned by no faction.
def set MyInitialRegions = FACTION_REGIONS(SelfID)

TERRITORY

Syntax: TERRITORY(x)
Returns: int, the ID of the faction that owns the point.

  • x: a coord, a unit (its position), or a city name (string).
if (TERRITORY(VIP)==SelfID)

LAND_SEGMENT

Syntax: LAND_SEGMENT(x [, map_type])
Returns: int, the land or water segment ID at the point.

  • x: a coord, a unit (its position), or a city name.
  • map_type: only when x is a coord. 0 standard map (default), 1 land map, 2 under-ice map.
def int MyLandSegment = LAND_SEGMENT("Dubai")

OCCUPIED_BY

Syntax: OCCUPIED_BY(x [, factions])
Returns:

  • One argument: the occupation bitscale: bit n set if faction ID n occupies it.
  • With factions: 1 if any of them occupies it, otherwise 0. factions is a faction ID, name, or a set of them.

x is a unit or a city name (string). SELECT form: see SELECT functions.

if (OCCUPIED_BY("Harbin", SelfID))

SIEGED_BY

Syntax: SIEGED_BY(x [, factions])
Returns: as OCCUPIED_BY, for sieges. Friendly factions and our own aren't marked in the bitscale.

if (CHECK_MASK(SIEGED_BY("Pyongyang"), ALLIES("South Korea")))
select cities OWNER==SelfID AND (NOT SIEGED_BY(PlayerID)) into AllFreeCities

POINT_OCCUPIED_BY

Syntax: POINT_OCCUPIED_BY(point [, factions])
Returns:

  • One argument: the faction ID of the closest unit whose occupation radius covers the point, or -1 if there is none.
  • With factions: 1 if a unit of any of them covers the point, otherwise 0.

point is a unit, a city name or a coord.

if (TERRITORY(ThisBase)==SelfID AND true!=POINT_OCCUPIED_BY(ThisBase, PlayerID))

TRANSFER_REGION

Syntax: TRANSFER_REGION(faction, regions [, faction, regions]+)
Returns: int, the number of regions transferred.

Transfers regions to a faction, with an announcement.

  • regions: a region name, region ID, or a set of them.
  • Several faction–regions pairs are handled at the same time: TRANSFER_REGION("USSR", {"Poland", "Germany"}, "United States", {"France", "Spain"}).

Reviving an inactive faction by transferring regions to it works in single-player only.

on each REGION_OCCUPIED ANY ->(string ThisRegion) BY ME TRANSFER_REGION("Pacified", ThisRegion)

ASSIGN_REGION

Syntax: ASSIGN_REGION(faction, regions [, faction, regions]+)
Returns: int, the number of regions assigned.

As TRANSFER_REGION, but silent, and the region then counts as originally owned by the new faction.

ASSIGN_REGION("Loyalists", LoyalistRegions, "Rebels", RebelRegions)

DESTROY_REGION

Syntax: DESTROY_REGION(regions)
Returns: int, the number of regions destroyed.

Destroys regions. regions as in TRANSFER_REGION.

DESTROY_REGION("South Korea")

HIGHLIGHT_REGION

Syntax: HIGHLIGHT_REGION(regions, color) · HIGHLIGHT_REGION(regions, r, g, b [, a]) · HIGHLIGHT_REGION(regions, false)

Highlights regions, or clears the highlight with false.

  • regions: a region name, region ID, or a set of them.
  • color: an RGB or RGBA string such as "FFFFFFFF", or explicit components 255, 255, 255, 255. A missing blue counts as 0.

Its result isn't a value: call it as a statement.

HIGHLIGHT_REGION(TheseRegions, "003000")
HIGHLIGHT_REGION(TheseRegions, false)

Map points

GET_VICINITY_POINTS

Syntax: GET_VICINITY_POINTS(target [, num [, owner [, region [, min_km [, spread_km]]]]])
Returns: set of random coord points around target.

  • target: the centre of the search: a coord, a unit or a city name.
  • num: how many points. Default 1, maximum 30.
  • owner: only points in this faction's territory. A faction ID or name, a unit (its owner) or a coord (the territory owner). -1 (default) or E1_UNDEFINED skips the check.
  • region: only points in this region. A region ID or name, a unit (its region) or a coord. -1 (default) skips the check.
  • min_km: minimum distance from the target. Default: half the map's minimum positioning distance, 25 km on vanilla maps.
  • spread_km: width of the ring, so points lie between min_km and min_km + spread_km. The default depends on num; 12.5 km for one point on vanilla maps.

The points are on the same surface as the target: water if the target is water, land if it is land.

It always returns num points. When it can't find enough, the missing points are set to target itself. Check for this if it matters.

def set DestinationPoints = GET_VICINITY_POINTS(Target, TotalArmiesHosted)
def set AroundCity = GET_VICINITY_POINTS(This, 5, E1_UNDEFINED, REGION_ID(RegionName), 50, 300)

VICINITY

Syntax: VICINITY(target [, num [, owner [, region [, min_km [, spread_km]]]]])
Returns: coord, one random point near target, on the same surface. If none can be found, target itself. The arguments are those of GET_VICINITY_POINTS.

unit ThisVIP move VICINITY(Target)

GET_RANDOM_POINTS_IN_REGION

Syntax: GET_RANDOM_POINTS_IN_REGION(region [, num [, avoid_units [, land_segment]]])
Returns: set of random coord points inside the region.

  • region: a region ID or name, a unit (its region) or a coord.
  • num: how many points. Default 1, maximum 128.
  • avoid_units: if non-zero, try not to place points near units.
  • land_segment: only points in this segment. Default -1, any segment.

It may return fewer points than requested.

def set InThisRegion = GET_RANDOM_POINTS_IN_REGION(Reg, Num, true)

AI_POINT

Syntax: AI_POINT(type [, target_factions [, replace_owner [, max_distance [, check_overlap [, faction_id [, region_id]]]]]])
Returns: coord of a point from the map's AI cache, or @(-1, -1) if there is none.

  • type: one of MissileSilo, CityDefence, Radar, OverHorizonRadar, Airbase, SubmarineAttack, SubmarineHide, CarrierAttack, MobileMissile, ObjectDefence, NavalBase, Orbit, Shore, CityControl, BorderDefence, MarinesLanding, AirborneTroopsLanding, TroopsTraining, Industry.
  • target_factions: the faction(s) the point is directed against; a set if several. Default: the factions at war with faction_id, otherwise its enemies, otherwise every other active faction.
  • replace_owner: true/false. If true, the same faction is used as both host and target faction.
  • max_distance: the AI point's effective range (int); 0 or less means unlimited. If nothing is found within it, the search is repeated without the limit.
  • check_overlap: true/false. If true, points that are already taken aren't returned.
  • faction_id: the faction the point is for (int). Default: the faction running the script.
  • region_id: only a point in this region. target_factions is then not used.
AI_POINT(Shore, SelfID, true, -1, true)

Missions

MISSION_STATE

Syntax: MISSION_STATE(name)
Returns: int, the mission state: m_InProgress, m_Success or m_Fail, or -1 if the mission isn't found.

if (m_InProgress==MISSION_STATE("Casualties"))

The library blocks MissionOK and MissionInProgress wrap it.

MISSION_COMPLETION

Syntax: MISSION_COMPLETION(name)
Returns: int, the mission's current progress as an absolute value (not a percentage), or -1 if the mission isn't found.

if (MISSION_COMPLETION("Scientists")>=2)

Sets

See also Sets for the set operators.

SIZE_OF

Syntax: SIZE_OF(set)
Returns: int, the number of elements.

A set used as an int gives its size anyway, so if (S) is the same as if (SIZE_OF(S) > 0); SIZE_OF is clearer. SIZE_OF(S) < 0 is always false.

if (SIZE_OF(FoundUnits)>0)

IS_EMPTY

Syntax: IS_EMPTY(set)
Returns: 1 if the set is empty, otherwise 0.

if (IS_EMPTY(AllSilos))

GET_ELEMENT

Syntax: GET_ELEMENT(set, i)
Returns: element i, counting from 0. An index out of range is undefined behaviour. Random access is slow on large sets; prefer ForEach.

def int GroupID = GROUP(GET_ELEMENT(FoundShips, 0))

GET_FIRST / GET_LAST

Syntax: GET_FIRST(set) · GET_LAST(set)
Returns: the first or last element. Undefined if the set is empty.

unit ThisSpecOps move GET_FIRST(Points)

DELETE_ELEMENT

Syntax: DELETE_ELEMENT(set, i)
Returns: element i, which is removed from the set. Index rules as in GET_ELEMENT.

def coord pt = DELETE_ELEMENT(SpawnPoints, RAND(SIZE_OF(SpawnPoints)))

DELETE_FIRST / DELETE_LAST

Syntax: DELETE_FIRST(set) · DELETE_LAST(set)
Returns: the first or last element, which is removed from the set. Undefined if the set is empty.

while (SIZE_OF(RegionsToCheck)>0)
  ThisRegion = DELETE_FIRST(RegionsToCheck)
  ...
end

SHUFFLE

Syntax: SHUFFLE(set_variable)
Returns: int, the size if the set was shuffled, otherwise 0. Shuffles the set in place.

SHUFFLE(RandomPoints)

REMOVE_DUPLICATES

Syntax: REMOVE_DUPLICATES(set_variable [, relaxed])
Returns: int, the number of duplicates removed. Works in place.

  • relaxed: if non-zero, compare like IN*: strings ignoring case, floats with a small error margin.
REMOVE_DUPLICATES(AllInvadedRegions)

INTERSECTION

Syntax: INTERSECTION(a, b [, relaxed])
Returns: set, the elements that are in both sets. relaxed as in REMOVE_DUPLICATES.

def set OurAdj = INTERSECTION(AvailableRegions, ADJACENT_REGIONS(ToInvade, SelfID))

UNION

Syntax: UNION(a, b [, relaxed])
Returns: set: a, plus the elements of b that aren't already in a. Unlike a + b, it doesn't add duplicates.

Targets = UNION(Targets, REGION_CITIES("Poland"))

XOR

Syntax: XOR(a, b [, relaxed])
Returns: set, the elements that are in exactly one of the sets.

def set Changed = XOR(StartRegions, FACTION_REGIONS(SelfID))    // won or lost since the start

Bit operations

A bitscale is an int in which bit n stands for faction ID n. Faction IDs run from 0 to 9; the functions below take bits 0–63. Visibility, alliance and occupation functions return bitscales.

  • GET_BIT(b, n): 1 if bit n of b is set, otherwise 0.
  • SET_BIT(b, n): sets bit n of the variable b to 1 and returns the new value.
  • CLEAR_BIT(b, n): sets bit n of the variable b to 0 and returns the new value.
  • GET_MASK(a, b): returns a AND b.
  • CHECK_MASK(a, b): 1 if a AND b is non-zero, otherwise 0.
  • SET_MASK(a, b): sets the bits of b in the variable a (a OR b) and returns the new value.
  • CLEAR_MASK(a, b): clears the bits of b in the variable a and returns the new value.

SET_BIT, CLEAR_BIT, SET_MASK and CLEAR_MASK change their first argument, which must be an int variable: SET_BIT(Seen, OWNER(Unit)).

def int MyAllies = Allies(SelfID)
select units false==GET_BIT(MyAllies, OWNER) AND DISTANCE(Start)<OCCUPATION_RANGE into EnemyUnits

UI and highlights

UI_STRING

Syntax: UI_STRING(id)
Returns: string number id from the localisation table.

Message UI_STRING(6242) Position TopLeft Portrait ADVISOR_PORTRAIT

HIGHLIGHT_POSITION

Syntax: HIGHLIGHT_POSITION(coord [, radius_km [, duration [, color]]])
Returns: int, the ID of the new highlight.

Sets a pulsing highlight (yellow by default) at a position.

  • coord: a coord, or anything that converts to one.
  • radius_km: default 50.
  • duration: the lifetime in ticks of real time, 60 per second, whatever the game speed and also while the game is paused: SECONDS(5) is five seconds on the clock. 0 or less (the default) means indefinite.
  • color: an RGB/RGBA string such as "FFFFFFFF", or explicit components 255, 255, 255 [, 255].
def int RangeHighlight = HIGHLIGHT_POSITION(TestRange, 100, SECONDS(30))

HIGHLIGHT_UNIT

Syntax: HIGHLIGHT_UNIT(unit [, radius [, duration [, color]]])
Returns: int, the ID of the new highlight, or 0 if the unit isn't found.

The same, for a unit or its ghost. The default radius comes from the unit's size and scaling; pass -1 to keep the default while setting a duration. The highlight ends when the unit stops being active.

def int H = HIGHLIGHT_UNIT(Flagship, -1, SECONDS(10), "FF0000")

CLEAR_HIGHLIGHT / CLEAR_ALL_HIGHLIGHTS

Syntax: CLEAR_HIGHLIGHT(id) · CLEAR_ALL_HIGHLIGHTS()

Removes one highlight (returns 1 on success, 0 otherwise) or all highlights (returns 1).

CLEAR_HIGHLIGHT(RangeHighlight)
CLEAR_ALL_HIGHLIGHTS()