Operators

C4Script nowadays supports most operators known from other programming languages (C/C++ style) or mathematics.
The usual operator priority applies (multiplication before addition and similar). For further information, see the table below.
Use brackets to force a specific operator priority.
The following operators are supported:
Priority Operator Description Location Type (resulting, expected)
17 ++ Increases the value of the preceding variable by 1. postfix (only one parameter) int, reference
17 -- Decreases the value of the preceding variable by 1. postfix (only one parameter) int, reference
16 ++ Increases the value of the following variable by 1. prefix reference, reference
16 -- Decreases the value of the following variable by 1 prefix reference, reference
16 ~ Bitwise negation of the following value prefix int, int
16 ! Logical negation of the following value prefix bool, bool
16 + no effect (compatibility for terms such as "+5") prefix int, int
16 - Yields the reciprocal of the following value. prefix int, int
15l ** Yields the power of a to b. postfix int, int/int
14l / Divides a by b. postfix int, int/int
14l * Multiplies a by b. postfix int, int/int
14l % Yields the remainder of the devision of a by b. postfix int, int/int
13l - Subtracts b from a. postfix int, int/int
13l + Adds a to b. postfix int, int/int
12l << Performs a bit shift operation to the left. postfix int, int/int
12l >> Performs a bit shift operation to the right. postfix int, int/int
11l < Returns whether a is less than b. postfix bool, int/int
11l <= Returns whether a is less than or equal to b. postfix bool, int/int
11l > Returns whether a is greater than b. postfix bool, int/int
11l >= Returns whether the first value is greater than or equal to the second. postfix bool, int/int
10l .. Concatenates two strings, converting the parameters to strings if necessary. postfix string, string|bool|int|id/string|bool|int|id
Concatenates two arrays. array, array/array
Extends the preceding map with values of the following one or overwrites values of already existing keys. map, map/map
9l == Returns whether a equals b. postfix bool, Any/Any
9l != Returns whether a is unequal to b. postfix bool, Any/Any
9l S= Returns whether two strings are identical. postfix bool, string/string
9l eq Also returns whether two strings are identical. postfix bool, string/string
9l ne Also returns whether two strings are not identical. postfix bool, string/string
8l & Performs a bitwise AND operation. postfix int, int/int
6l ^ Performs a bitwise XOR operation. postfix int, int/int
6l | Performs a bitwise OR operation. postfix int, int/int
5l && Performs a logical AND operation. postfix any, any/any
4l || Performs a logical OR operation postfix any, any/any
3l ?? Yields the following value if the preceding value is nil, otherwise yields the preceding value. available with #strict 3 or higher postfix any, any/any
2r **= Exponentiates the preceding variable by the following value postfix reference, reference/int
2r *= Multiplies the preceding variables by the following value postfix reference, reference/int
2r /= Divides the preceeding variable by the following value postfix reference, reference/int
2r %= Sets the preceding variable to the remainder of the division of that variable by the following value postfix reference, reference/int
2r += Increases the preceding variable by the following value postfix reference, reference/int
2r -= Decreases the preceding variable by the following value postfix reference, reference/int
2r <<= performs a bitwise left-shift on the preceding variable by the following value postfix reference, reference/int
2r >>= performs a bitwise right-shift on the preceding variable by the following value postfix reference, reference/int
2r ..= Appends the following string to the previous one (both parameters are converted if needed) postfix reference, reference/string|bool|int|id
Appends the following array to the previous one. reference, reference/array
Extends the preceding map with values of the following one or overwrites values of already existing keys. reference, reference/map
2r &= Performs a bitwise AND operation. postfix reference, reference/int
2r |= Performs a bitwise OR operation. postfix reference, reference/int
2r ^= Performs a bitwise XOR operation. postfix reference, reference/int
2r ??= Assigns the following value to the preceding variable only if the variable is nil. available with #strict 3 or higher postfix reference, reference/any
2r = Assigns the following value to the preceding variable postfix reference, reference/any

Explanation and examples:

Postfix or prefix?

This property of an operator determines whether it is used before (pre) or after (post) its parameter.
Prefix operators only have one parameter while postfix operators usually have two parameters (one preceeding and one following). See also operators ++/--.

Example 1:

Log(" Ergebnis: %d", 5 + 5);
Log(" Ergebnis: %d", 12 - 5);
Log(" Ergebnis: %d", 5 * 5);

Output:

 Ergebnis: 10
 Ergebnis: 7
 Ergebnis: 25
Addition, subtraction, multiplication, division, and similar form the group of postfix operators. They combine the two values preceeding and following the operator.

Example 2:

Log(" Ergebnis: %d", -(5 + 5));
Log(" Ergebnis: %d", ~7);
Log(" Ergebnis: %d", !0);

Output:

 Ergebnis: -10
 Ergebnis: -8
 Ergebnis: 1
Prefix operators are located before the value to which they are applied.

Operators ++ and --

Operators ++ and -- exist as both postfix and prefix operators. The postfix version of these operators does not have a second parameter.

Example 1 (postfix):

Var(0) = 0;
while(Var(0)++ < 10)
  Log("%d", Var(0) )

Example 2 (prefix):

Var(0) = 0;
while(++Var(0) < 10)
  Log("%d", Var(0) )
These two examples are almost identical. In both cases the value of Var(0) is increased by one per loop repetition. The result is compared to 10 in each case.
Yet there is an important difference between the two versions: when using the postfix version, the previous value of the variable is returned. The first example will result in a count from 1 to 10, since at beginning of the last loop repetition is value of Var(0) is 9. It is then increased by one (Var(0) is now 10) but the previous value of 9 is returned and compared to 10. Thus the loop will be repeated one more time and then the value of 10 is printed.
In the second example, on the other hand, the loop runs from 1 to 9. When Var(0) is 9 and is increased, the new value of 10 is returned immediately. The result is not less than 10 and the loop ends.

Operators && and ||

These two operators are special since #strict 2. If the result is already known after evaluating the first parameter, the second parameter is not evaluated at all. For example an object doesn't explode from the following script because the result will always be 0 regardless of the result of Explode:
0 && Explode(20);
Furthermore, the result of the operator is either the first or the second parameter, depending on how far the evaluation was necessary. For example, in the following way it is possible to create a knight falling back to creating a clonk if creating the knight failed:
CreateObject(KNIG,0,0,GetOwner()) || CreateObject(CLNK,0,0,GetOwner())

Operators ?? and ??=

?? is known as nil-coalescing operator in some programming languages. Both operators check if the preceding value is nil. Only if it is nil the following expression is evaluated and the result is returned or stored respectively. Otherwise ?? returns the preceding value and ??= does not change the variable. These are typically used for default values or fallback values of function calls which may return nil. In contrast to || the check is spefically against nil and without conversion to bool.
These operators are only available with #strict 3 or higher, just as nil.

Examples:

1337 ?? 42; // = 1337
nil ?? 42; // = 42
0 ?? 42; // = 0
0 || 42; // = 42

// Standardwert für x ist 10, 0 kann aber explizit übergeben werden.
func Foo(int x)
{
	x ??= 10;
}
				

Operators .. and ..=

These two operators have different meaning depending on the parameter types. .. und ..= work exactly the same way, except that the latter directly modifies the preceding variable.

String Concatenation

For parameters of types string, bool, int and id a string concatenation is performed. ints and ids are therefore converted to their usual textual representation, whereas bools are also represented as ints. The following example logs "Lesefortschritt: 40 %" (german for reading progress):
Log("Lesefortschritt: " .. 3 + 1 .. 0 .. " %");

Array Concatenation

If both parameters are arrays array concatenation is performed. The following examples results in [1, 2, 3, 10, 20, 30]:
[1, 2, 3] .. [10, 20, 30]

Map Concatenation

If both parameters are maps, the preceding map is extended with the values of the following map. This means, that keys that do not exist in the preceding map get added with the corresponding value, whereas the values of keys existing in both maps are set to the value stored in the following map. This way it is possible specify default values as follows:
var defaults = { Message = "To lazy to think of my own!", Color = RGB(255) };
var settings = defaults .. { Message = "Hello there!", Italic = true };
// settings will be { Message = "Hello there!", Color = RGB(255), Italic = true }

Priority and Associating

This subject shows how operator priority is evaluated in detail.
To calculate the result of a complex term, first we have to decide in which order to evaluate the individual operations and to which other operator the result is to be passed.
Generally, operators with a higher priority are evaluate before operators with a lower priority. Notice: this does not apply to the evaluation of parameters - those are normally evaluated from left to right.

Example:

Log("%d", 5 * 4 + 3 < 6);
evaluated as:
Log("%d", (((5 * 4) + 3) < 6));
Here we have another problem: what to do when 'neighbouring' operators have the same priority? Should we first process the left or the right term? This is decided by the so called associativity. If an operator is left-associative then the term on the left is evaluated first (this is the usual case). With right-associative operators the term on the right is evaluated first.

Example:

Var(0) = Var(1) = 1 + 2 + 3 + 4;
evaluated as:
Var(0) = (Var(1) = (((1 + 2) + 3) + 4) );
Here you can see that the operator "+" is left-associative, the term "1 + 2 + 3" is evaluated as "(1 + 2) + 3".
As opposed to this, the term "Var(0) = Var(1) = x" becomes "Var(0) = (Var(1) = x)", since the operator "=" is right-associative.
To find out about an operator's associativity, see the table above.

Bit Manipulation Operators

In the operator list you will have noticed some operators which perform bitwise operations or bit shift.
To start out, a short description of bits: any computer internally works with 'binary numbers'. In this system there are only two digits: 0 and 1. Humans, by the way, usually work with 10 digits: 0 to 9. With the binary system, number can be represented as follows:

The Binary System

(each number is presented in the decimal system first, then binary)
1 = 00000001
2 = 00000010
4 = 00000100
8 = 00001000
6 = 00000110
7 = 00000111
Each digit in the binary system is called a "bit". A sequence of 8 bits (see above) is called a "byte".
Bitwise operatiors perform actions on the bits of a number.

Example:

~00000000 = 11111111
~00000100 = 11111011
~01100000 = 10011111
This example shows a binary NOT. That means, each bit of the number is negated individually (0 becomes 1, 1 becomes 0).
Bitwise operators with two parameters combine the bits of two numbers.

Examples:

10010010
& 01110111
= 00010010
10010010
| 01110111
= 11110111
10010010
^ 01110111
= 11100101
These three operators are (in order) AND (&), OR (|) and EXCLUSIVE-OR (^).
With the AND operator, the resulting bit will only be 1 if both incoming bits are 1. AND gives the following result:
& 0 1
0 0 0
1 0 1
The OR operator results in 1 if one or both of the incoming bits are 1:
| 0 1
0 0 1
1 1 1
The XOR operator results in 1 if either (but not both) of the incoming bits are 1.
^ 0 1
0 0 1
1 1 0

Applications

Clonk often uses bitwise operations when storing the characteristics of an object in a single value. The best known example is the category ("C4D" values) of an object. Here, each bit of the category value represents a certain class or characteristic.
To access or sort out the individual characteristics, you can easily access a C4D value with bitwise operators:

Example (wipf):

Category = 69640
This value in binary system:
10001000000001000
You can see that bit 3, 12, and 16 are set (counting from left to right, starting with 0).
This represents the C4D values C4D_Living (objects is a living being), C4D_SelectAnimal (living being can be selected in the menu system) and C4D_TradeLiving (living being can be bought or sold).
In script you can now easily check whether a given bit is set: simply use the AND operator () with a second parameter ("mask"). In this mask, only a single bit is set, representing the category value which we we like to test for. In the result of the AND operation all bits that do not interest us, will be 0. Only the one bit that does interest us, has the chance of being 1 - that is, if it is set in the original value. Since a single bit set in a number will already cause that number's value to be different from 0, all you have to do now is to compare the resulting number to 0: if it is different from 0, the characteristic we have been looking for is given; if the result is equal to 0, the characteristic is not given.

Example:

10001000000001000 (value)
& 00001000000000000 (mask)
= 00001000000000000
In this case, the result is unequal to 0, so we know the bit we have set in the mask is also set in the original value.
10001000000001000 (value)
& 00000000010000000 (mask)
= 00000000000000000
Here the result is equal to 0, meaning the bit we are looking for was not set in the original value.
The question remains where to get the proper mask from. In the case of the C4D categories, there are predefined values we can use. They are called C4D_xxx. So to find out whether an object is a living being we use the following code:
if (GetCategory() & C4D_Living)
  ;...;
Now we can test whether an individual bit is set. But how can we change bits, for example set them? For this, we can use the OR operator (|). Again, it is applied using a value and a mask as a second parameter:
10001000000001000 (value)
| 00000000010000000 (mask)
= 10001000010001000 (new value)
In this way it is only possible to set a certain bit to 1. If the bit was already set, the value will remain unchanged. To set a certain bit to 0 we have to use the AND operator and the inverse (logical NOT) mask, or [value] &~[mask]:
10001000010001000 (value)
& 11111111101111111 (= ~00000000010000000)
= 10001000000001000 (new value)
It is also possibly to toggle a certain bit from 1 to 0 or 0 to 1, whichever way it is set. This is done with the XOR operator (^):
10001000000001000 (value)
^ 00000000010000000 (mask)
= 10001000010001000 (new value)
10001000010001000 (value)
^ 00000000010000000 (mask)
= 10001000000001000 (new value)

Bit Shifts

Besides operators for bitwise combination of values there are also the bit shift operators. All these operators do is move all the bits in a number from left to right (adding a new 0 on the left) or from right to left (adding a new 0 on the right).

Example:

  00001000000001000 << 2
= 00100000000100000

  00001000000001000 >> 2
= 00000010000000010
Mathematically, the operator << performs a multiplication by 2 (exactly in the same way that in the decimal system appending a 0 performs a multiplication by 10) and the operator >> is a division by 2 (including some rounding).
Using these operators you can put together masks (1 << bit-no.) and mix or take apart RGB color values.
PeterW,