An operator is something that takes one or more values (or expressions) and yields another value (so that the construction itself becomes an expression)
Operators can be grouped according to the number of values they take. Unary operators take only one value, for example
! (the logical not operator). Binary operators take two values, such as the familiar arithmetical operators
+ (plus) and
- (minus). The majority of Ghost's operators fall into this category.
Precedence and Associativity
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression
1 + 5 * 3, the answer is
16 and not
18 because the multiplication (
*) operator has a higher precedence than the addition (
+) operator. Parentheses may be used to force precedence, if necessary. For example,
(1 + 5) * 3 evaluates to
When operators have equal precedence their associativity decides how the operators are grouped. For example,
= is left-associative, so
1 - 2 - 3 is grouped as
(1 - 2) - 3 and evaluates to
= on the other hand is right-associative, so
a = b = c is grouped as
a = (b = c).
Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
The following table summarizes the operator precedence in Ghost, from highest to lowest. Operators in the same box have the same precedence.
||Grouping, Method call||Left|
||Multiply, Divide, Modulo||Left|
||Equals, Not equal||Left|
Remember basic arithmetic from school? These work just like those.
The result of the modulo operator (
%) has the same sign as the dividend - that is, the result of
a % b will have the same sign as
a. For example:
print(5 % 3) // >> 2 print(5 % -3) // >> 2 print(-5 % 3) // >> -2 print(-5 % -3) // >> -2
Declaration and Assignment Operators
The declaration operator is
:=. This declares a new variable and assigns the value of the expression on the right.
message := "Hello, world!" print(message) // >> Hello, world!
The basic assignment operator is
=. This is NOT the same as "equal to". It means that the left operand gets set to the value of the expression on the right. Assignments can only be used on declared variables.
a := 0 // Declare the variable "a" and set the value to 0 print(a) // >> 0 a = (5 + 10) // Assign the new value (5 + 10) to the pre-declared variable "a" print(a) // >> 15
Comparison operators, as their name implies, allow you to compare two values.
||Less than or equal to||
||Greater than or equal to||