Help

Order Script
Language
  - Header
  - Macros
  - Output
  - Warnings
  - Context Specifiers
  - Statements
  - Arrays
  - Global variables
  - Line breaks
  - Comments
Running scripts
  - Arguments
  - Run time
  - Manual scripts
Expression Syntax
  - Operand types
  - Evaluation Context
  - Brackets
  - Operators
  - Precedence
  - Logic Optimization
Regular expressions
Symbols
  - All contexts
  - Regex context
  - Region context
  - Unit context
  - Faction context
  - Troop context
  - Object context
  - Item context
  - Skill context
Change Log

Registration

gnawer@newmail.ru
http://gnawer.byte-force.yar.ru

File version 3.21.6

Order Script

Note: scripts available in registered version only.

Unit orders may be customized by scripts. Typical script may look like this:

#script Train horses
clear // clear unit orders
if Skill("horse training") 
  if Region.Products("horses") > 0
    produce "horses"
  else
    i = 1
    while (i <= 6) & (!Region.HasExit(i) _
     | (Region.Neighbour(i).Terrain = 'ocean'))
i = i + 1 end if i <= 6 move (Dir(i)) end end else work end

There is script header (#script), statements (bold), comments (gray), symbols (brown), context specifiers (green), user-defined variables (red) and output (teal). You may include many scripts in single file, each with specific "#script" header.

Header

Script must start from "#script" header. Header format:

#script [default_run_time] Script Name (default_args)

Default_run_time is optional and specifies default order before which script will run. Default_args is optional and specifies default arguments.

Macros

Macro commands may be defined similar to scripts. Macros starts with #macro header and included in place marked by #insert directive. Macros may include another macros, if latter was defined above in text.

Script Will return
#macro Macro1
N = N + 1

#script Test
N = 1
#insert Macro1
(N)
2

Output

Each string which not starts with statement or variable assignment considered as output. For unit scripts, output is the area between "@;script Name" and "@;end Name" marks (see Attaching to units). Variables and expressions may be included in output in brackets.

Script Will return
N = 10
buy (N) plainsmen
buy 10 plainsmen

Warnings

You may send warnings to Order Processor Errors window. To do it, include following into output:

@;warning Warning_Message

Actually, @;warning is not a script symbol and not recognized by script; that's rather the order token which may be similarly used without any scripts (for example, in TURN construction).

Context specifiers

Predefined symbols typically evaluated in specific context. For unit scripts, default context is unit with the script. For region warnings, default context is region. So, "Name" in unit context will return unit name and in region context will return nothing.

You can change context for a symbol, preceding it with context specifier. It's somewhat similar to object in object-oriented language. For example:

Wages = 10 in region context

is similar to

Region.Wages = 10 in unit context

Some functions may act as context specifiers.

Script Will return
Region(31, 35, "surface").Land Fetlar

Statements

Each statement must start at beginning of the line.

assignment Variables may be defined in expression like "A = 10" and used later.

if expression
...
else
...
end

Condition statement. Else is optional. See Expression syntax for explanations of expression part.
for identifier = start_expression to end_expression
...
end
Loop control statement. Evaluates the expressions once and then repeats loop, assigning to identifier values from start_expression to end_expression. Expressions must evaluate to number. If start is greater than end (for i = 10 to 0), identifier will be decreased on each step.
while expression
...
end
Loop control statement. Repeats while expression is true. Expression is evaluated on each iteration, therefore it works slower than FOR.
with symbol
...
end
Execute block in context of symbol.
do expression Executes expression (i.e. do units(55).delorder(5))
exec script_name (args) Executes other script with given arguments on same output
clear Clears output area in unit orders.

Note that with statement is not just adds prefix to symbols. Advisor will evaluate symbol for with once, remember it, and then use it without evaluation for all symbols inside block. This might significantly speed up script execution.

Script Evaluates following
X = Region("31 12 1").ForSale - 1
while X > 0
  buy 1 (Region("31 12 1").ForSale(X).Short)
  X = X - 1
end

Region (quite time-consuming)
ForSale
Region
ForSale(2)
Region
ForSale(1)
Region
ForSale(0)

with Region("31 12 1")
  X = ForSale - 1
  while X > 0
    buy 1 (ForSale(X).Short)
    X = X - 1
  end
end

Region
ForSale
ForSale(2)
ForSale(1)
ForSale(0)

Arrays

OrderScript supports one-dimensional arrays. You don't need to declare arrays or manage their lengths. When you assigning value to array-type variable, this starts new array; accessing index outside declared ones producing "range check error".

Script Will return
a[0] = 'uhus'
a[2] = 'jabba'
for i = 0 to 3
  (a[i])
end

uhus

jabba
Range check error on index 3

a[0] = 'uhus'
a[1] = 'jabba'
for i = Low(a) to High(a)
  (a[i])
end

uhus
jabba

Global variables

You may set global variables which will be visible in all scripts, even after program restart. These variables are stored in [ScriptVariables] section of game.ini.

Script Will return
do SetGlobal("advisor", "rulez")
(Global("advisor"))

rulez

Line breaks

If a line ends with underscore ("_"), it will be glued to next one.

Line Equal to
Region("31 35 _
  1").Land
Region("31 35 1").Land

Comments

Comments must start from double slash (//) - in C style.

Running scripts

You may attach a script to unit, so it will run any time unit's orders being processed. To do this, open unit's context menu, select Scripts, then script name. Actually, by doing this, you inserting following text in unit's orders:

@;script [run_time] Script Name (argument0, argument1...)
(output)
@;end Script Name

Run_time part may differ from default defined in script. Actual run time is determined by given here in orders. Arguments are also optional. All normal output will go to output area (lines before @;end line). If there's no @;end line, output area is all the lines till end of orders. Note that output area will not be cleared before script execution.

Script 1st run result 2nd run result
Hello Void Hello Void Hello Void
Hello Void
clear
Hello Void
Hello Void Hello Void

Output area will be parsed for scripts after script execution; so, script may write another @;script tag to output and this inserted script will be executed too.

Run time

If no run time specified for a script, Advisor will run script and then do all order processing. There is some special values (see table). This option allows scripts, for example, to issue STUDY orders if unit claims enough money earlier in this turn.

Script Will run
#script Test before any orders
#script [buy] Test before BUY orders
#script [monthlong] Test before monthlong orders
#script [final] Test after all orders
#script [startup] Test once on game start*
#script [manual] Test when user selects it from Scripts menu

* [startup] scripts will run once when Advisor opens new turn and doesn't finds orders for it; but when you assigning [startup] script to an unit, all [startup] scripts in the unit's region wil re-run once more. All other scripts, except [manual], will re-run each time Advisor re-runs orders in region.

To understand this, imagine order processing. First, Advisor takes unit as it was in report.

* Unit (324), Faction (22), plainsman [PLAI]. (orders: "claim 200")

First-time scripts may run now and return that unit hasn't any silver. Then, Advisor processes orders and come to following processed unit:

* Unit (324), Faction (22), plainsman [PLAI], 200 silver [SILV]. (orders: "claim 200")

"Final" script will now return that unit has 200 silver.

Note that if script runs after some orders, and gives orders of that type to unit, that orders will not be processed. Generally scripts should not run later than most early order they can issue.

Script Will result
#script Test
claim 200
unit claims 200 silver
#script [monthlong] Test
claim 200
unit don't claim

This is important only for Advisor order handling, server will process orders as usual.

Arguments

Arguments may be read in script as "args(N)" values.

N = args(1)

Manual scripts

Manual scripts can't be attached to units and will not appear in unit menu; they appears in Scripts menu and executes in context of currently selected unit (it must be player's unit). Output for such script is the selected unit's orders. When selected, they execute immediately (on processed unit), so their run time is similar to [final]. After execution of a manual scripts, Advisor will:

  1. Store all orders;
  2. Recreate all player's units;
  3. Process all orders again (orders issued by the script will be processed too).

Expression Syntax

Expression evaluated as set of operands divided by operators.

Operand types

numbers 10, -10 integer numbers
strings "uhus sux" quoted strings delimited by single or double quotes
variables A user-defined identifiers; must start from letter; may contain letters (A..Z), numbers (0..9) and underscore ( _ )
symbols Region.HasExit("N") predefined constants and functions. Functions has set of parameters in brackets. Parameters may be of any type, including function: fn(fn2(10), 2) is valid.

All operands except strings are case-insensitive.

Note: symbols cannot be target of assignment.

Region.Land = "Fetlar" is invalid

Evaluation context

If all operands evaluated to numbers, expression will evaluate in integer context, otherwise it will evaluate in string context.

Script Will return
2 + "2" + "uhus" "22uhus"
2 + "2" + 10 14

Brackets

Brackets changes precedence of operators. Contents of each brackets evaluated in specific evaluation context.

Script Will return
2 + 4 * 10 42
(2 + 4) * 10 60
2 + (2 + "uhus") "22uhus"
(2 + 2) + "uhus" "4uhus"

Operators

Evaluation context is determined by operands only, operators does not taken into account. Some operators are not valid in every context.

Valid in logical context: !, &, |, =, != or <>, >, <, >=, <=
Valid in number context: +, -, *, /, ~, all logical
Valid in string context: +, ~, all logical

A ~ B means "Position of B in A". First char is 1; if no B found in A, returns 0. This operator always assumes operands as strings.

Number operators always work with integers, so 3 / 2 = 1.

Logical operators, except "=" and "<>", always works in logical context regardless of whole evaluation context. That is, they takes left and right side as boolean expressions. Empty string (""), "0", 0, "false" and symbol false evaluates to False, all other expressions evaluates to True. Result of logical operations is 0 in number context or "" in string context for False and 1 or "1" for True.

Script Will return
2 & 2 true & true = true
0 | "uhus" + 1 false | true = true
true + "1" = "11"

There is two unary operators: ! (not) and - (minus).

2 + -2 is correct and = 0
2 + !2 is correct and = 2, because !2 = False = 0
2 + !-2 is still correct and = 2
2 + -!2 is incorrect

Precedence of operators:

  1. !
  2. *, /, &, ~
  3. +, -, |
  4. =, !=, >, <, >=, <=

Logic Optimization

Advisor optimizes logical chains in expressions. For example, if we have expression like "1 | (Region.Units.Count > 0) | whatever", we don't need to fully evaluate it, because we know result by first operand. In other words, "TRUE or ..." is always true and "FALSE and ..." is always false. Advisor will evaluate such expressions only until first significant operator and skip all other. For example, "1 & 2 & 0 & 3" will be evaluated until 0; 3 will be skipped.

Regular expressions

There is one embedded object for regular expressions. To work with it, set Regex context. Syntax of regular expressions is not subject of this document, see other available sources for this topic. Here is some examples.

Script Will return
cnt = Regex.Exec("(\w+) eats (\w+)", _
  "Uhus eats Jabba")
(cnt)
(Regex.Match(0))
(Regex.Match(2)), (Regex.MatchPos(2))
 
3
Uhus eats Jabba
Jabba, 11
cnt = Regex.Exec("\w+", "Uhus eats Jabba")
(cnt)
(Regex.Match(0))
cnt = Regex.ExecNext
(cnt)
(Regex.Match(0))

1
Uhus
1
eats
(Regex.Replace("Uhus Sux", "\w{3}$", _
  "Rules"))
Uhus Rules

Modifiers may be added through (?...) construction, so:

Expression Will match
uhus uhus
(?i)uhus

uhus
Uhus
UHUS

Symbols

If symbol requires an item or skill name as argument, it may be either short name ("STON") or full name ("stone").

Troop stays for part of faction, located in given region.

Name Sample Value

All contexts

ArgsCount   Count of passed arguments
Args(idx) Args(0) Specified argument
Global(name) Global("uhus") Get global variable
SetGlobal(name, value) SetGlobal("uhus", "sux") Set global variable
true   "1" (string), 1 (number)
false    "" (string), 0 (number)
eval(str) eval(" 1 + " + " 2 ") = 3 Evaluates string and returns evaluation result
bool(x) bool("uhus") = 1 Returns boolean value of expression
Dir(n)

Dir(1) = "N"
Dir(2) = "NE"
Dir(3) = "SE"
Dir(4) = "S"
Dir(5) = "SW"
Dir(6) = "NW"

Direction string
LevelIndex(name) LevelIndex("surface") Z-coord for specified level; may return 0 for first level, if no level found returns ""
Length(s) Length("foobar") = 6 Length of string
Substr(s, idx, count) Substr("foobar", 1, 3) = "foo" Substring
Low(array)   Lowest index of array
High(array)   Highest index of array
Turn   Turn number
Random(range)   Integer random number 0 <= X < range
RemoveScript   Removes script command @;script ... @;end from orders. Script output are remains in place.
Regex   Sets context to regex object
Unit(num) Unit(345) Sets context to an unit and returns unit number if unit found
Faction(num) Faction(345) Sets context to a faction and returns faction number if faction found
Region(coords) Region("0 0 0") Sets context to a region and returns region coords if region explored
AllItems   Count of list of all known items
AllItems(idx)

AllItems(0)
AllItems("SILV")
AllItems("silver")

Sets context to item and returns item short name
AllSkills   Count of list of all known skills
AllSkills(idx) AllSkills(0)
AllSkills("PATT")
AllSkills("pattern")
Sets context to skill and returns skill short name
AllObjects   Count of list of all known objects

AllObjects(idx)

AllObjects(0)
AllObjects("Tower")

Sets context to object and returns object type

LeaderMaintenance 20 Values configured for current game in Options.
PeasantMaintenance 10
EntertainIncome 20
TaxIncome 50
StudentsPerTeacher 10
HealsPerMan 5
FlyingCrossWater True
Unclaimed   Amount of unclaimed silver
Regex context
Exec(pattern, string) Exec("\d+", "123") Executes pattern on string; returns count of matches
Match(idx) Match(0) Returns match for pattern defined in Exec. Match(0) is whole pattern, Match(1) and more is groups in brackets.
MatchPos(idx) MatchPos(0) Returns character position for match
ExecNext   Find next match
Replace(string, pattern, replacement) Replace("foobar", "f.o", "bar") = "barbar" Replace pattern with replacement
Region context
X   X coord
Y   Y coord
Level surface Name of map level
Coords 21 13 1 X Y Z
Terrain plain  
Land Fetlar  
Visible   Player's units currently exploring this region
Explored   This region was explored (visited sometimes)
Exit(dir) Exit("NE") If there is exit in specified direction, sets context to neighbor region and returns coords; otherwise returns False.
Settlement Canna Name of settlement
SettlementType city city, town, village
Peasants PLAI Sets context to peasants as item and returns short name or race.
TaxRate    
Wages    
MaxWages    
Entertainment   Entertainment available
Gate   Number of gate, if any
Guard 147 Number of guarding faction
Weather clear Weather for next month
Battles   Amount of battles in region
Notes    Region notes
MoveCost(dir, movement) MoveCost("N", "walk") Move Points to enter the neighbour region (1 for plain and clear, 4 for forest and winter)
NextNew   Next number for new unit to use in FORM. Available for any run-time, including before FORM order.
Wanted   Count of items wanted
Wanted(idx)

Wanted(1)
Wanted("wine")

Sets context to item and returns item amount

ForSale   Count of items for sale
ForSale(idx) -"- Sets context to item and returns item amount
Products   Count of products
Products(idx) -"- Sets context to item and returns item amount
Objects   Count of objects
Objects(idx) Objects(1) = 123

Sets context to object and returns number of object

Troops   Count of factions in region
Troops(idx) Troops(1) = 123 Sets context to troop and returns faction number
Unit context
Name    Unit name
Num    Unit number
Description    Unit description

OnGuard
Autotax
Avoid
Behind
Hold
Noaid
Nocross

   Unit flags
Consume consume
consume unit
consume faction
Consuming flag
Reveal -"- Revealing flag
Spoils spoils all
spoils none
spoils walk
spoils ride
spoils fly
Spoils flag
Region 12 10 1 Sets context to region and returns coords
TradeIncome    
WorkIncome    
Faction 124 Sets context to unit faction and returns faction number
Troop 124 Sets context to unit troop and returns faction number
Object 1 Sets context to object and returns object number
CombatSpell FIRE  
Former 1223 Sets context to unit formed this one (for "new 1" units formed this turn) and returns unit number
Items   Count of items in inventory
Items(idx) Items(1)
Items("WOOD")
Sets context to item and returns item amount
IsMage    
LocalDescription    
SetLocalDescription(value)   Change local description of the unit
Skills   Count of skills
Skills(idx) Skills(1)
Skills("PATT")
Sets context to skill and returns skill level
CanStudy   Count of CanStudy
CanStudy(idx) CanStudy(1) = "NECR" Short of I-th CanStudy
AmountOf(flag) AmountOf("man") Amount of items of given type. Allowed types is: "wagon", "silver", "man", "monster", "magic", "weapon", "armor", "mount", "tool", "cantgive", "resource", "advanced", "food", "trade"
Load(move) Load("walk") Load of item for specified movement type (see Load tab on Unit tab in main window). Allowed types is: "walk", "ride", "fly", "swim"
Capacity(move) Capacity("ride") Capacity for specified movement type
UsedWagons   Wagons which has Horses
MovementType "walk"
Normal movement (walking, riding or flying); returns False if unit can't move.
Taxers   Amount of tax-ready men (with combat skill or weapon)
AllOrders   All orders in single line (including added by the script)
MonthOrder    
DelOrder(line) do DelOrder(1) Delete specified line from orders. Doesn't return anything.
InsOrder(line, text) do InsOrder(0, "move N") Insert line in orders. Doesn't return anything.
Orders   Count of order lines
Orders(idx) Orders(1) I-th order line
Events   Count of events
Events(idx) Events(1) I-th event (if first symbol is "!", that's error, if not - event)
Faction context
Name   Faction name
Num   Faction number
Attitude "Unfriendly"  
Units   Count of units throughout the world
Units(idx) Units(1) = "new 1" Sets context to unit of the faction and returns unit number
Troop context
Name   Faction name
Num   Faction number
Attitude "Unfriendly"  
Units   Count of units in region
Units(idx) Units(1) = "new 1" Sets context to unit of the faction in the region and returns unit number
Object context
Name Gold Fish Object name
Num   Object number
Description    
Needs    
Type Longboat Type name
Defence   Object is a defence structure (Castle)
Transport   Object is a transport (Longboat)
Flying   Object is flying (Balloon)
Closed   Closed to player's units
InnerLocation   Contains an inner location
Road   Is a road
Link 21 12 2 Sets context to linked region and returns region coords (for shafts)
Direction NE Returns direction of road as string
Size   Amount of material to build
Protection   For defstructures - amount of men protected
Capacity   For transports - carried weight
Sailors   For transports - man/skill levels to control
Material1 WOOD Build material
Material2 STON Alternative build material
BuildSkill SHIP Sets context to skill to build and returns skill short name
Resource GRAI For trade structures - resource aided
Load    
Owner   Sets context to owner unit and returns unit number
Item context
Amount   Amount for sale/wanted/to produce
Cost    
Name sea elvis Item name
Short SELF  
Wagon
Silver
Man
Monster
Magic
Weapon
Armor
Mount
Tool
Cantgive
Resource
Advanced
Food
Trade
  Item flags
Description   Item description
Weight    
Capacity(move) Capacity("walk") Note that walking items must carry their weight, so men (weight 10, capacity 5) will actually have Capacity("walk") = 15. Allowed movements are: "walk", "ride", "fly", "swim"
ProduceSkill LUMB Sets context to skill to produce this item and returns skill short name
ProduceRate   Rate: amount of items
ProduceManMonths   Rate: time to produce these items
ProduceMaterials   Count of items in list
ProduceMaterials(idx) ProduceMaterials(1)
ProduceMaterials("WOOD")
Sets context to item and returns item amount
MagProduceSkill ARTI Sets context to skill to magically produce the item and returns skill short name
MagProduceRate    
MagProduceMaterials   Count of items in list
MagProduceMaterials(idx) MagProduceMaterials(1)
MagProduceMaterials("WOOD")
Sets context to item and returns item amount
ManLeader   This is a leader
ManDefLevel   Default skill level
ManSpecLevel   Special skill level
ManSpecSkills   Count of special skills
ManSpecSkills(idx)

ManSpecSkills(1)

Sets context to skill and returns skill short name
WpnNeedSkill   Weapon needs skill
WpnNoFoot   Can't be used on foot
WpnNoMount   Can't be used on mount
WpnShort   Short
WpnLong   Long
WpnRanged   Ranged
WpnNoAttackerSkill   Attacker's defence is 0 regardless of Combat skill
WpnRidingBonus   Riding bonus for Attack and Defence
WpnRidingBonusDefence   Riding bonus for Defence only
WpnNumAttSkill   Number of attacks relies on skill
WpnNumAttHalfSkill   Number of attacks relies on skill/2
WpnClass "slashing", "cleaving"...  
WpnAttackType "melee", "energy"...  
WpnSkill1 XBOW Skill to use weapon (if needed)
WpnSkill2 LBOW  
WpnAttackBonus    
WpnDefenceBonus    
WpnMountBonus   Additional bonus when attacks mounted opponent
WpnNumAttacks   Number of attacks per round (2 means 2 per 1 round, -2 means 1 per 2 rounds)
ArmorUseInAss   Use the armor in assassination
ArmorDefence(idx) ArmorDefence("slashing") Percents of defence
MountSkill   Skill to use mount in battle (usually Riding)
MountMinBonus   Minimal skill level to use in battle
MountMaxBonus   Maximal -"-
MountMaxHamperedBonus   Maximal bonus for flying mounts if terrain doesn't allow flying
ToolAddsTo   Count of items aided
ToolAddsTo(idx)

ToolAddsTo(1)
ToolAddsTo("BAG")

Sets context to item and returns item amount (meaning production bonus)
Skill context
Level 1 Learned level
Days 30 Days learned
Name weaponsmith  
Short WEAP  
Description(level) Description(1) Description for specified level
Cost   Cost to learn per month
Common   Skill is learned by common people
Magic   Skill is learned only by mages
Foundation   Foundation skill
CombatSpell   May be assigned as combat spell
Cast   May be cast
BasedOn   Count of base skills
BasedOn(idx)

BasedOn(1)
BasedOn("PATT")

Sets context to skill and returns skill level

Change Log

Changes in v 3.21.6  
[startup] runtime Previously fired on each turn load; now fired only on first turn load when no orders found (same with Needs autodistribution)
Changes in v 3.20.4  
LeaderMaintenance Added
PeasantMaintenance Added
EntertainIncome Added
TaxIncome Added
StudentsPerTeacher Added
HealsPerMan Added
FlyingCrossWater Added
Unclaimed Added
Changes in v 3.20.2  
arrays Added
Low Added
High Added
exec statement Added
Changes in v 3.18.1
Item.ManSpecLevel Obsolete; still supported for backward compatibility
Item.ManSpecSkills Behavior changed
Item.ToolAddsTo Removed
Unit.UsedWagons Removed