 |
 | | |
Unary, binary, etc | | |
|
Operators can appear before, after and between factors.
When you think about it, mathematical expressions are basically numbers (the factors in this case) connected by operators.
Most high-level languages have between twenty to thirty operators, but there's no need to go over them all at this time.
You should know, however, that we don't differentiate operators by their symbol alone.
The minus sign (-) for example stands for two separate operations.
In a mathematical expression, the minus symbol could mean either negation or subtraction.
We categorize operators on the number of "arguments" or factors they use, for example unary, binary, ternary and so on.
|
 |
-a -- unary minus
a - b -- binary minus
|
 | | |
Precedence and associativity | | |
|
You take it for granted that the computer can correctly calculate an expression like 1 + 2 * 3.
It's smart enough to multiply 2 and 3 before adding 1 to the result.
This means something very important.
The computer will always follow the statements of your script from top to bottom, however, the individual operations within a statement have their own order of "precedence" and are not always executed from left to right.
|
 |
|
 | | |
| | |
|
Precedence is a measure of the "priority" of the different operators.
As already noted, multiplication has higher precedence than addition (negation has even higher, by the way).
Associativity explains how two operators of the same type behave when they appear one after another in a single expression.
Most mathematical operators (like addition, subtraction) are "left associative" which means that their left-hand side will be calculated first.
The most notable, right-hand associative operation is assignment (=).
|
 |
-- left-associative
1 - 2 - 3
-- means (1 - 2) - 3
-- right-associative
a = b = 5
-- means a = (b = 5)
|
 | | |
Return types | | |
|
Operators are not just used for mathematical expressions.
Appending one string at the end of another can be done using the concatenation operator (..).
Remember that all operations except for assignment do not change the value of the variables involved.
This is also true for concatenation, except that it returns a string result that you can store in another variable.
There are also a number of comparison operators such as less then (<), greater than (>), equal (==), not equal (~=) and so on.
These operators always return a Boolean value.
Comparison operators behave differently depending on the types of factors involved.
The expression a == b will tell you whether the two factors have the same value.
However, the equality of a and b depends on the sort of data that they both contain.
For example, a string containing the number five is not equal to a variable with a numeric value of five.
|
 |
a = "Mr."
b = "Smith"
c = a .. b
-- c equals "Mr.Smith"
|
 | | |
|
Next: Data types
|
 | | |
|
|