Wesnoth Formula Language

From The Battle for Wesnoth Wiki
Revision as of 21:14, 4 March 2016 by Celtic Minstrel (talk | contribs) (New page about the formula language, drawing in information from FormulaAI and the source code)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The Wesnoth Formula Language is a functional language used to evaluate expressions within the game engine. The most common use of the WFL is in the $(formula) substitution syntax, but it can also be used in unit filters, GUI2 dialogs, and even AI.

Numbers

The most common use of WFL is for simple calculations involving numbers. For this, the standard arithmetic operators (+ - * / %) work as you would expect, performing addition, subtraction, multiplication, division, and remainder. The only caveat to watch out for is that / rounds down when used on integers. For example, 5 / 2 will evaluate to 2. To avoid this, make sure at least one of the numbers includes a decimal point - 5.0 / 2 will evaluate to 2.5. Note that WFL supports only three decimal places of precision; beyond that it will still be rounded down. (So 1.0 / 16 will evaluate to 0.63 instead of 0.625.)

You can also use the standard comparison operators (= != < <= > >= on numbers. This is often useful in unit filters - for example, a formula of hitpoints < max_hitpoints / 2 will match only if the unit is at less than half health. Comparison operators return 1 for true and 0 for false; there is no boolean type.

Strings

WFL also supports strings, which must be enclosed in single quotes ('like this'). The comparison operators also work on strings, performing lexicographical comparison (ie, alphabetical order). The comparison is case sensitive.

Lists

A list is a sequence of values represented as square brackets, [], surrounding a comma-separated list. For instance:

[ 1, 5, 'abc' ]

The comparison operators work on lists, performing lexicographical comparison. A specific list index can be obtained with the indexing operator, like this: my_list[index]. The first element of a list is numbered 0.

Maps

Maps: A map is a sequence of key-value pairs. For example:

[12 -> 'Hello', [1,2] -> 9, 'abc' -> 1.5]

The comparison operators work on maps. A specific element of a map can be obtained with the indexing operation. In the above example, the following conditions are all true (assuming the map is in a variable called self):

  • self[12] = 'Hello'
  • self1,2 = 9
  • self['abc'] = 1.5