Difference between revisions of "Wesnoth Formula Language"

From The Battle for Wesnoth Wiki
(Link to GUI2 page)
(concatenate: Correct explanation of function)
Line 232: Line 232:
 
=== concatenate ===
 
=== concatenate ===
  
* concatenate(''string1''[, ''string2'', ...])
+
* concatenate(''value1''[, ''value2'', ...])
  
Returns a new string consisting of all the input strings concatenated together.
+
Converts each of its arguments to a string, and concatenates the result together into a single string.
  
 
=== contains_string ===
 
=== contains_string ===

Revision as of 20:03, 11 March 2016

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.

Data Types and Operators

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.063 instead of 0.0625.) The ^ operator performs exponentiation (raising to a power) - for example, 2 ^ 3 evaluates to 8

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.

One final numeric operator exists - the dice roll. The syntax 3d12 will roll three 12-sided dice and return the sum of the results. Note however that this is not multiplayer-safe, so using it can and will produce OOS errors.

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.

There are four vector operators (.+ .- .* ./) that perform entrywise operations on lists. For example, [1,2,3] .+ [12,2,8] produces [13,4,11]. Both lists must be of the same length to use these operators.

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'
  • self[[1,2]] = 9
  • self['abc'] = 1.5

Objects

An object is a container containing additional variables (see below for further explanation of variables) which are not in the global scope. The dot operator can be used to evaluate a formula in the object's scope. For example, suppose u is a unit object referring to your leader, who is an Elvish Ranger who has taken 12 damage (thus has 30 hit points). Then u.hitpoints will evaluate to the number 30. For a more advanced example, u . (hitpoints < max_hitpoints - 10) will evaluate to true if the unit has taken more than 10 damage, which in this example, it has. (This could also be written u.hitpoints < u.max_hitpoints - 10 if you prefer; this enters the scope twice, instead of once, but the result is identical.)

Objects generally cannot be created directly by the code - they are created for you by the game when formulas are called in certain contexts. However, there are two types of object that can be created by your code. The first is the location object, which has variables x and y; it can be created by the loc() function. The second is the map pair object, which is returned (or used internally) by several of the built-in functions and has variables key and value.

Other Types and Operators

There is one other basic type in WFL - the null type, which is used to mean "no value". It will be returned if you attempt to perform an invalid operation, such as dividing a string. It is also returned by the built-in null() function, which allows you to test if a value is null by writing value = null().

The logical operators and and or can be used to connect conditional expressions, and the unary operator not negates them. Note that or is inclusive - A or B is false only if both A and B are false. These operators consider 0 or null to be false, while all other values count as true. The if() function also follows the same rules to determine whether a value is true or false.

Note: Programmers familiar with other languages may be surprised by the fact that and and or do not short-circuit (which would mean that they will never evaluate their second argument if they can know their result solely from the first argument). This should not be a problem in general formula usage, since functions do not have side-effects, but in FormulaAI where some functions do have side-effects it could make a difference.

Operator Precedence

The precedence of various operators is, more or less, what you'd expect - you can write something like a + b * 2 <= 5 and c - d / 4 > 7 and the engine will do what you expect - first multiplication and division, then addition and subtraction, then comparison, and finally logical conjunction. The only thing to watch out for is when chaining exponentiation - all operators are left associative, so a ^ b ^ c will be evaluated as (a ^ b) ^ c instead of a ^ (b ^ c) like you would expect.

The full precedence list is as follows, from lowest to highest; operators on the same line have equal precedence.

  1. not
  2. where clauses
  3. or
  4. and
  5. Comparison operators = != < <= > >=
  6. Additive operators + -
  7. Multiplicative operators * /
  8. Modulus %
  9. Exponentiation ^
  10. Dice operator d
  11. Dot operator .

Variables

Formulas may have a variety of variables, depending on the context in which they are evaluated. A string substitution formula like $(3 + 5) has no variables, but a unit filter formula has variables such as hitpoints and max_hitpoints which contain various properties of the unit being tested (the same unit which is also referred to in variable substitution as $this_unit). The special variable self typically refers to the "global context" - in the case of a unit filter formula, the unit itself. This means for example that self.hitpoints and hitpoints are equivalent when used in a unit filter formula. In a string substitution formula, self is null.

A formula may declare additional variables using a where clause. This assigns a meaning to any unknown variables in the preceding formula. The general syntax is:

<formula> where <variable> = <value> [, <variable> = value ...]

This functions similarly to an operator, so if desired, you could have multiple where clauses in a single formula. Note that all variables in WFL are read-only - they are variables because they may have different values depending on the context in which the formula is evaluated, but for a given context, they are constant. A variable that has not been assigned a value is considered to have a value of null.

Variable names can contain letters and underscores only. In particular, they cannot contain digits. Also, names are case-sensitive, so y and Y refer to two different variables.

Comments

Sometimes with particularly complicated formulas, it may be useful to document what's going on inline. Of course, you can use WML comments to do this, but in some cases it may be useful to put some comments in the middle of the formula. This is easily done - simply enclose them in # characters, like this:

#This is a Wesnoth Formula Language comment.#

Note the final # - unlike WML, WFL requires this to indicate where the comment ends.

Functions

There are several predefined functions in the Wesnoth Formula Language, and if these are not enough, it is possible to define your own functions. The special variable functions always evaluates to a list of all known function names. This is mainly useful only as a debugging tool, though.

To define a function, you use the def keyword. For example:

def sgn(x) if(x < 0, -1, x > 0, 1, 0);

This defines a function called sgn which returns the sign of the input number. The semicolon marks the end of the function. It's optional if there's nothing else following the function, but in practice this will very rarely be the case.

You can select one of the function's arguments to be the "default" argument. If an object is passed to the default argument, then any attributes of that object are directly accessible in the global scope. For example:

def is_badly_wounded(u*) hitpoints < max_hitpoints / 2;

This function takes a unit and returns 1 if it is at less than half hitpoints. The * indicates the default argument, without which it would instead have to be defined like this:

def is_badly_wounded(u) u.hitpoints < u.max_hitpoints / 2;

Note: As of 1.13.4, function definitions only work in AI code; however, this is likely to change in the future.

Core Functions

Many of the core functions exhibit two features that (as of 1.13.4) cannot be used in user-defined functions. The first is the ability to accept a varying number of arguments - some core functions accept any number of arguments, while others have a few options arguments. The second is that arguments are lazily-evaluated, and in some cases some arguments will not be evaluated at all, while others may be evaluated multiple times with different variable values. The description of each function will explain how and when its arguments are evaluated.

Conditional Functions

There are two functions which return one of their input values based on some condition - the if function, and the switch function. Both evaluate only as many parameters as is needed to determine which value to return. In particular, parameters that are neither returned nor part of the condition will never be evaluated.

if

  • if(condition, if true [, condition 2, if true 2, ...] [, otherwise])

This function first evaluates the condition, which is a formula. If it evaluates to true, then the function evaluates and returns the if true parameter; otherwise, it tries the next condition (if any) with the same result. If none of the conditions evaluate to true, then it returns the otherwise parameter if present, or null() otherwise.

For instance, an AI that recruits Wolf Riders on the first turn, and Orcish Grunts thereafter might look like this:

if(turn = 1, recruit('Wolf Rider'), recruit('Orcish Grunt'))

switch

  • switch(formula, value 1, outcome 1 [, ... , value N, outcome N] [, default outcome])

The switch function first evaluates the input formula, and then checks if it is equal to any of the specified values. If matching value is found, the outcome assigned to it is returned; if not, then function returns either default outcome (if specified) or null.

Numeric Functions

Several basic math functions are available. These generally work equally on integer and decimal values.

abs

  • abs(number)

Returns the absolute value of an input number; for example

abs( -5 )

will return 5.

as_decimal

  • as_decimal(number)

Ensures that the number is a decimal rather than an integer; useful if you're dividing two unknown values and want to ensure that the result is a decimal.

ceil

  • ceil(number)

Returns the ceiling of the specified number, ie rounding it up to the nearest integer.

cos

  • cos(angle)

Returns the cosine of the given angle, which is specified in degrees.

floor

  • floor(number)

Returns the floor of the specified number, ie rounding it down to the nearest integer.

max

  • max(list of numbers)

Returns the largest number from the list. For example:

max([2, 8, -10, 3])

will return 8.

min

  • min(list of numbers)

Returns the smallest number from the list. For example:

min( [ 3, 7, -2, 6] )

will return -2.

round

  • round(number)

Returns the specified number rounded to the nearest integer.

sin

  • sin(angle)

Returns the sine of the given angle, which is specified in degrees.

sum

  • sum(list of numbers)

This function evaluates to the sum of the numbers in the list of numbers. For example:

sum([ 2, 5, 8])

returns 15, and:

sum(map(my_units, max_hitpoints - hitpoints))

finds the total damage your units have taken.

wave

  • wave(number)

Given a numeric value V, this returns:

 sin(2*pi/(V%1000/1000))

String Functions

There are a few useful functions for manipulating strings.

concatenate

  • concatenate(value1[, value2, ...])

Converts each of its arguments to a string, and concatenates the result together into a single string.

contains_string

  • contains_string(string, search_string)

Returns 1 if search_string can be found within string (as a substring), 0 otherwise. For example:

contains_string( 'Testing', 'ing' )

returns 1.

length

  • length(string)

Returns the length of the input string.

substring

  • substring(string, offset[, size])

Extracts a substring from the given input string. The offset specifies the first character to extract; the first character is 0, and negative values count from the end, so the last character is -1. If specified, the size indicates the total number of characters to extract; it cannot be negative. If omitted, all characters from the offset to the end of the string are returned. For example:

substring('The quick brown fox jumps over the lazy dog!', 4, 5)
substring('The quick brown fox jumps over the lazy dog!', -9, 4)
substring('The quick brown fox jumps over the lazy dog!', -9)

return 'quick', 'lazy', and 'lazy dog!' respectively.

List and Map Functions

This section contains functions that directly manipulate a map or list.

head

  • head(list)

Returns the first item from the list; for example

head([5, 7, 9])

returns 5.

head( [ 'Orc', 'Human' ] )    #returns 'Orc'

index_of

  • index_of(value, list)

This function will return the first index where value can be found in the input list. It will return -1 if the value is not found in the list'.

keys

  • keys(map)

Extracts the key values from an input map and returns them as a list. For example:

keys(['Elvish Fighter' -> 50, 'Elvish Archer' -> 60])

returns

['Elvish Fighter', 'Elvish Archer']

size

  • size(list)

This function returns the number of elements in the list.

For example, size([5, 7, 9]) returns 3 and size(['Archer', 'Fighter']) returns 2.

sort

  • sort(list, formula)

This function evaluates to a result list sorted according to the comparison formula for each item a and its successor b. For instance, sorting units according to hitpoints would be done by:

sort(my_units, a.hitpoints > b.hitpoints)

To sort them in the reverse order, simply use < instead of >.

tolist

  • tolist(map)

This function takes a map and return a list of key-value pair objects. For example:

tolist(['Elf' -> 10, 'Dwarf' -> 20])

will return:

[{key->'Elf',value->10}, {key->'Dwarf',value->20}]

tomap

  • tomap(list A [, list B])

This function takes one or two lists as input and returns a map. If only one list is specified, then the function will evaluate this list, count how many similar elements are found within the list, and return a map with keys being these elements, and values being a number representing how many of them the list contains. For example:

tomap(['elf', 'dwarf', 'elf', 'elf', 'human', 'human'])

will return:

['elf' -> 3, 'dwarf' -> 1, 'human' -> 2]

If two lists are specified, then the elements of the first one will be used as a keys, and the elements of the second one as a values, when creating an output map. Note that these input lists must be of the same length. For example:

tomap(['elf', 'dwarf' ], [10, 20])

will result in:

['elf' -> 10, 'dwarf' -> 20]

values

  • values(map)

Extracts the values assigned to keys from an input map and returns them as a list. For example:

values(['Elvish Fighter' -> 50, 'Elvish Archer' -> 60])

returns

[50, 60]

List-processing Functions

This section covers functions that operate on maps or lists by applying one or more formulas in succession to each element. Most return another map or list, reduce instead combines all the elements into a single result.

choose

  • choose(input, [self_name,] formula)

This function evaluates formula for each item in the input (which can be a list or a map). It will return the first item to which formula gave the highest value. For example:

choose(my_units, level)

gives back the unit with the highest level.

The implicit input when evaluating a mapping/filtering function's formula component will be that specific item under evaluation (in this example one of "my_units"), and it can be explicitly referenced as self when necessary. The optional <self_name> parameter can be used to give a different name to the self variable.

When evaluating a map, we can reference each key by key and each value by value. In this case, the self variable is this key-value pair. For example:

choose(['elf' -> 10, 'dwarf' -> 20 ], value)

will return a key-value pair

{key->'dwarf', value->20}

The curly braces are used in output to indicate that this is an object, not a map. It is not valid WFL syntax.

filter

  • filter(input, [self_name,] formula)

This function will run the formula on each item in the input (which can be a list or a map). It will evaluate to a list or map which only contains items that the formula was true for. The optional <self_name> parameter can be used to give a different name to the self variable.

filter(my_units, hitpoints < max_hitpoints)

will return all of your units which have less than maximum hitpoints. For instance this could be used if looking for candidates for healing.

find

  • find(input, [self_name,] formula)

This function will run <formula> on each item in the <input> (which can be a list or a map) and will return the first item for which <formula> was true. The optional <self_name> parameter can be used to give a different name to the self variable. For example:

filter(units, id = 'Elvish Archer' )

will return the first unit with id equal to 'Elvish Archer'.

map

  • map(input, [self_name,] formula)

This function will run the formula on each item in the input (which can be a list or a map), and evaluate to a new list or map or a map, which contains the same number of items as in input, with the formulas run on each item. The optional <self_name> parameter can be used to give a different name to the self variable. When run on a map, the resulting map has the same keys as the input map, but with the values updated to the results of the formula. For example:

map([10,20], self*self)

and

map([10,20], 'value', value*value)

will both result in [100, 400]. The formula:

map(my_units, hitpoints) 

will give a list back with the number of hitpoints each unit has. This is more useful in conjunction with other functions.

map(['elf' -> 10, 'dwarf' -> 20 ], value*2)

The above will produce ['elf' -> 20, 'dwarf' -> 40]. Note that in case of a map data type, the map function can only modify the value.

map(tomap([3,5,8,8]), value+key*100)

The above will produce [3 -> 301, 5 -> 502, 8 -> 801]. This can be used to take a list and make a map containing pairs [element_from_that_list -> f(element_from_that_list,number_of_repetitions_of_that_element_in_that_list)] where f is an arbitrary function.

reduce

  • reduce(list, formula)

This function will run the formula on the first and second members of the list, then on the result and the third member and so on until the list is depleted. The final result is then returned. The two variables used in the formula are always 'a' and 'b'.

For example, reduce([1,2,3,4], a+b) returns 10 and reduce([9,4,8,2], 10*a+b) returns 9482.

Miscellaneous Functions

Some functions really don't fit into any category. They are all listed here.

loc

  • loc(x, y)

Creates and returns a location object with the specified coordinates. If assigned to a variable pos (eg with a where clause), the individual coordinates can be accessed as pos.x and pos.y.

null

  • null([arguments])

Evaluates each of its arguments (if any) in order, then returns null. Since formulas generally do not have side-effects, there is little point in specifying any arguments unless you are writing AI code (where several functions do have side-effects).

Debugging Functions

There are also a few functions that can be useful for debugging formulas, for example by displaying intermediate results to the screen. Note that this breaks the general rule that functions do not have side-effects.

debug

  • debug([formula])

Starts a GUI formula AI debugger when evaluating a formula. It takes a formula, evaluates it and returns the result unchanged. Note: this does not appear to work in 1.13.3.

debug_print

you need to enable formula log (--log-info='ai/formula_ai') to see the result of this call

  • debug_print([explanation ,] formula )

This function can be used for debugging a formula. It takes a formula, writes its result to the console, and returns it unchanged. For example:

debug_print([1, 2, 3])

will result in printing to the console

[1, 2, 3]

and returning the same.

We can specify an optional parameter explanation that helps to distinguish between multiple debug_print calls in the same formula:

debug_print('My array: ', [1, 2, 3])

will write in the console:

My array: [1, 2, 3]

and return

[1, 2, 3]

debug_float

  • debug_float(location, [explanation,] formula )

This function can be used for debugging a formula. It takes a formula, floats a label containing the result on the hex specified (in the same way damage is displayed) and returns it unchanged. Note that the location here is an object type; it can be created with the loc() function. For example:

debug_float(me.loc, me.id)

will make a label containing the id of the unit me float over the unit.

Return value is also the unit id.

We can specify an optional parameter explanation that helps to distinguish between multiple debug_float calls in the same formula:

debug_float( me.loc, 'id: ', me.id )

will float the following label

id: unit_id

and return the unit id.

dir

  • dir(object)

This function return a list of all attributes in object. For example:

dir(my_leader)

will result in the following output:

[ 'x', 'y', 'loc', 'id', 'leader', 'hitpoints', 'max_hitpoints', 'experience', 'max_experience', 'level',
'total_movement', 'movement_left', 'side', 'is_enemy', 'is_mine']

This command is useful in the formula command line, to get information about the attributes of different types of data.