foreach (roll option)

From MapToolDoc
Jump to: navigation, search

FOREACH Option

Introduced: Version 1.3.b46

Iterates over the contents of a string list in the format "item1, item2, item3". Can also be used easily with JSON arrays and JSON objects. String Property Lists can be processed with a couple of extra functions.

Usage

  1. [FOREACH(var, list): body]
  2. [FOREACH(var, list, output_separator): body]
  3. [FOREACH(var, list, output_separator, list_separator): body]

output_separator default value is null
list_separator default value is ",". Some examples of other useful separators: nothing "", space " " and break "<br>".

Examples

String List Example

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

JSON Array Example

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

JSON Object Example

(Note that using foreach with a JSON object will result in only the keys being returned as vars).

  1. [h: enemyList = json.set("","Orcs", "Bob, Dave", "Goblins", "Graham", "Ogres", "Philip, Emanual", "Trolls", "Ig, Og, Ug")]
  2. [FOREACH (enemy, enemyList, "<br>"): "You really hate " + enemy]

All the above will output:

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

Using with [code():] and output_separator

To use roll options with your FOREACH loop, you will need to use [code():] roll option. In this example I have separated the results with the string " then ".

[h: enemyList="Orcs; Goblins; Ogres; Trolls"]
[FOREACH(enemy, enemyList, " then ", ";"), CODE:
    {
    [r: enemy]
    }
]

output:

Orcs then Goblins then Ogres then Trolls

String Property List Example

  1. [h: enemyStrProp = json.toStrProp(json.set("","Orcs", "Bob, Dave", "Goblins", "Graham", "Ogres", "Philip, Emanual", "Trolls", "Ig, Og, Ug"))]
  2. [FOREACH(enemy, enemyStrProp, "<br>", ";"), code:
  3. 	{
  4. 	[h: enemyList = stringToList(enemy, "=")]
  5. 	[h: name = listGet(enemyList, 0)]
  6. 	[h: value = listDelete(enemyList, 0)]
  7. 	[r: "You really hate " + name + " who are " + value]
  8. 	}
  9. ]

output:

You really hate Orcs who are Bob, Dave
You really hate Goblins who are Graham
You really hate Ogres who are Philip, Emanual
You really hate Trolls who are Ig, Og, Ug

See Also

json.append(), json.set(), [code():], stringToList(), listGet(), listDelete()