Macros:Branching and Looping

From MapToolDoc
Jump to: navigation, search
INTERMEDIATE
THIS IS AN INTERMEDIATE ARTICLE

Introduction

This page details the branching and looping structures in MapTool. With the exception of the block if() statement, these are all roll options and should follow the general form for roll options:

  1. [option1[,option2]: body]

These may be combined with other roll options (note that in some examples, they are combined with the Hidden Roll option (h) to hide the default output of the loop or branch).

If you wish to combine roll options in a single statement, separate the roll options with a comma, and place the colon at the end of the sequence of roll options. Note that some combinations have unpredictable results, such as using [if():] with [macro():].

For example, if you want to combine a Hidden Roll, [token():], and [foreach():] option in a single statement, you would enter the line like so:

  1. [h,token("JoeRandom"),foreach(item, TokensItemList): "This item's name is "+item+"!"]


Branching

IF Option

Introduced: Version 1.3.b46

This [if():] is a roll option (as mentioned above), but operates similarly to the block-style if().

Usage

  1. [if(condition): true_body; false_body]
or
  1. [if(condition): true_body]

Either the true_body or false_body will be used, depending on the value of condition. If the false_body is not given but the condition is false(0), then there is no output.

Example

  1. [h:val=12]
  2. [h,if(val == 12): newVal=12*12]
  3. New Value = [r:newVal]

Outputs New Value = 144.

Note

For an alternate method for evaluating "if" conditions, see the function if(). Note that the [if():] roll option cannot be (usefully) combined with the [macro():] roll option as the roll options are not guaranteed to be executed in any particular order. This means that the if() function is a better choice in those cases.

SWITCH Option

Introduced: Version 1.3.b46

[switch():] chooses among several options and executes code based on the switch expression.

  • Note that the expression is a regular expression, so metacharacters such as * and () will need to have backslashes in front of them if you want to match them literally.

Usage

  1. [switch(expression):
  2. case case1: body1;
  3. case case2: body2;
  4. default: default_body]

or with a code block:

  1. [switch(expression), code:
  2. case case1: {body1};
  3. case case2: {body2};
  4. default: {default_body}]

Example

  1. [h:powerType="at-will"]
  2. [switch(powerType):
  3.   case "at-will": "You may use this power as much as you like";
  4.   case "encounter": "You may only use this power once per encounter";
  5.   case "daily": "You may only use this power once per day"
  6. ]

Outputs You may use this power as much as you like

Using a code block:

  1. [h:powerType="at-will"]
  2. [switch(powerType), code:
  3. case "at-will": {
  4.     [r:token.name]:<br>
  5.     [r:"You may use this power as much as you like"]
  6.   };
  7. case "encounter": {
  8.     [r:token.name]:<br>
  9.     [r:"You may only use this power once per encounter"]
  10.   };
  11. case "daily": {
  12.     [r:token.name]:<br>
  13.     [r:"You may only use this power once per day"]
  14.   };
  15. ]

Using regex:

  1. [h:powerType=".*sword.*"]
  2. [switch(powerType):
  3.   case "flail": "one-handed weapon; two-handed does Str*2 damage";
  4.   case "shortsword": "used for jabs, so is a puncturing weapon";
  5.   case "longsword": "a slashing weapon"
  6. ]

Outputs used for jabs, so is a puncturing weapon. Notice that the first matching clause was the one that the [switch():] option found.

MACRO Option

Introduced: Version 1.3.b46

[macro():] runs the named macro, inserting its text into chat.

Usage

  1. [macro("macro_name@location"): macro_arguments]

The called macro sees a variable called macro.args which contains the value of macro_arguments. The called macro can set a variable called macro.return, which becomes available to the calling macro. Other than macro.return, the called macro shares no variables with the calling macro.

Examples

  1. [macro("getDamage@Lib:combat"): damageRoll]

Calls the macro getDamage which resides on a library token called Lib:combat, and passes the variable damageRoll as an argument to the called macro.

Location Requirements

The location can be one of the following:

  1. TOKEN - the currently impersonated token (use the word TOKEN, not the token's name)
  2. Library Token - a Library Token in the current campaign
  3. this - if the macro is calling another macro in the same library, this may be used instead of retyping the full library token name

Notes

When a token macro calls another macro, the macro instructions in the called macro are executed against the calling token (in other words, the macro uses properties available on the calling token and applies all results to that token), unless the focus is explicitly changed to another token via either a roll option, or the switchToken() function, or the getLibProperty() function.

Also, as of at least 1.3.b50, a variable must be given for macro_arguments, or the "Could not execute the command: Undefined function: MACRO" error will result. However, the variable given as macro_arguments doesn't have to be used.

TOKEN Option

Introduced: Version 1.3.b48

[token():] executes a series of instructions against a token specified in the argument rather than against the token running the macro.

This is a temporary change in the token that has the "focus" - only the instructions following the colon are applied to the designated token; following the end of that instruction block, operations resume being performed against the token running the macro.

To permanently switch (for the duration of the macro) the token against which macro commands are executed, see the switchToken() function.

Usage

  1. [token(token_identifier): ]

Executes the roll against token specified by token_identifier, which can either be the token name or token id.

Examples

  1. [h:target="Orc 5"]
  2. [h,token(target): targetAC = getProperty("AC")]

Uses the getProperty() function to retrieve the property AC from the token named "Orc 5", and assigns that value to the variable targetAC. targetAC can be used in future calculations, such as determining whether an attack hits. If the [token():] option was not used, the macro would have looked for the property AC on the token currently running the macro. Note also that this function is considered trusted.

Looping

COUNT Option

Introduced: Version 1.3.b41

The [count():] option executes a statement for a specified number of times, storing the number of the current iteration in a variable called roll.count.

Usage

  1. [count(num): body]
  2. [count(num, separator): body]

The roll.count variable will take on values from 0 to (number of loops - 1). The optional separator (default ",") is printed between each iteration.

Example

  1. [h:numHits=3]
  2. [count(numHits): Damage = Damage + 1d12]

This will iterate the Damage = Damage + 1d12 operation 3 times, separating the result of each iteration with the default separator (a comma). An optional second argument to [count():] allows the setting of a different separator.

FOR Option

Introduced: Version 1.3.b46

Executes a statement for a number of iterations based on a start and end value.

Usage

  1. [for(var, start, end): body]
  2. [for(var, start, end, stepsize): body]
  3. [for(var, start, end, stepsize, separator): body]

The var variable counts from start to 1 short of end during the loop (so the end number will not be part of the loop). The optional stepsize (default +1) is added to var at each iteration. The loop does not evaluate when var reaches end.

Example

  1. [for(i,10,0,-2): "i is now " + i]

Counts down even numbers from 10 to 2.

FOREACH Option

Introduced: Version 1.3.b46

Iterates over the contents of a string list in the format "item1, item2, item3", the contents of a JSON Array, or the keys of a JSON Object.

Usage

  1. [foreach(var, list): body]
  2. [foreach(var, list, output_separator): body]
  3. [foreach(var, list, output_separator, list_separator): body]
  4. [foreach(var, jsonarray): body]
  5. [foreach(var, jsonarray, output_separator): body]
  6. [foreach(var, jsonobject): body]
  7. [foreach(var, jsonobject, output_separator): body]

Example Using a List

  1. [h: enemyList="Orcs, Goblins, Ogres, Trolls"]
  2. [foreach(enemy, enemyList, "<br>"): "You really hate " + enemy]

Outputs:

You really hate Orcs
You really hate Goblins
You really hate Ogres
You really hate Trolls

Example Using a JSON Array

  1. [h: weapons = json.append("[]", "Longsword", "Dagger", "Bow")]
  2. [foreach(wpn, weapons): wpn]

Outputs:

Longsword, Dagger, Bow

Example Using a JSON Object

  1. [h: weaponData = json.set("{}",
  2.     "Name": "Longsword",
  3.     "Damage": "1d6",
  4.     "Type": "Slashing",
  5.     "Weight": 30,
  6. )]
  7. [foreach(field, weaponData): field]

Outputs:

Name, Damage, Type, Weight

If you really wanted to see the key and the data, try this:

  1. [h: weaponData = json.set("{}",
  2.     "Name": "Longsword",
  3.     "Damage": "1d6",
  4.     "Type": "Slashing",
  5.     "Weight": 30,
  6. )]
  7. [foreach(field, weaponData):
  8.     field + ": " + json.get(weaponData, field)]

Outputs:

Name: Longsword, Damage: 1d6, Type: Slashing, Weight: 30

P.S.: Note the trailing comma after the Weight field in the json.set() function? It's ignored. But putting it in makes it easier to copy/paste new lines into the function...

WHILE Option

Introduced: Version 1.3.b46

Repeatedly executes a statement until a condition becomes false.

Usage

  1. [while(condition): body]
  2. [while(condition, separator): body]

Example

  1. [h:num=10]
  2. [while(num>=0): num = num-1]

Outputs 9,8,7,6,5,4,3,2,1

Code Execution

CODE

Introduced: Version 1.3.b46

The [code():] option is used in conjunction with looping / branching options to execute multiple statements within a single "block" of a loop or branch, allowing the creation of more complex loops and branches.

Usage

  1. [code: { code_block }]

The code_block is a collection of text and macro code, enclosed in a single {} pair. Everything within the {} is treated as a single block for the purposes of any looping or branching options.

Example

  1. [h:num=5]
  2. [while(num > 0), code:
  3. {
  4.   This is iteration [r:num] <br>
  5.   There are [r:num-1] iterations left<br>
  6.   [num=num-1]
  7. }]

Outputs:

This is iteration 5 There are 4 iterations left
4, This is iteration 4 There are 3 iterations left
3, This is iteration 3 There are 2 iterations left
2, This is iteration 2 There are 1 iterations left
1, This is iteration 1 There are 0 iterations left
0

NOTE: the digit output at the beginning of each line is an artifact of the [while():] loop's evaluation of num - since this roll does not have the [h:] option active, the result of that evaluation is displayed.

Nested CODE Blocks

To nest code:{} blocks, use a second [code():] option, like so:

  1. [h:d20roll=1d20]
  2. [h:attackRoll=d20roll+AttackBonus]
  3. [h,if(attackRoll >= 16),code:
  4. {
  5.   [if(d20roll == 20),code:
  6.   {
  7.     The attack is a critical hit!
  8.     [h:damage=critDamage]
  9.   };
  10.   {
  11.     The attack is a hit!
  12.     [h:damage=regDamage]
  13.   }]
  14. };
  15. {
  16.   The attack misses!
  17. }]

MapTool can only handle two levels of nested code.

Additions

Conditional Operators:

  • > - Greater than
  • < - Less than
  • >= - Greater than or equal to
  • <= - Less than or equal to
  • == - Equal to
  • != or ne - Not equal

Logical Operators:

  • && - And
  • || - Or

Boolean Operators:

  • true
  • false

It is important to note that the Equal condition operator must be two equal signs. If you are checking for a text string, place quotes around the text.

Operator Precedence:

  • ( ) - Parentheses are always done first; they can be nested
  • ! - Logical NOT
  • &, ^, and | - Bitwise AND, XOR, and OR (left to right)
  • && - Logical AND
  • || - Logical OR