Squirrel Expressions

From SigMod
Jump to navigation Jump to search
BACK
HOME
NEXT

Expressions are combinations of literals, variables, and operators which are evaluated to return a single value, which can then be used in variable assignment or other tasks.

printl(1 + 2 + 3); // 1 + 2 + 3 is an expression which evaluates to the integer 6, 6 is then printed to the console

local x = 500.0 / 2; // 500 / 2 is an expression which evaluates to 250.0, 250.0 is then assigned to x

With all the working parts, especially the operators, you might wonder how the compiler knows what order to parse your code in, or what order of operations to adhere to. This is called operator precedence, which determines what operators are called first over others in the same expression. You can view the Squirrel Precedence List in the Squirrel Reference Manual. Keep in mind you should use this as a reference, don't try to memorize the whole list, it's not necessary.


Concerning precedence, there a few things that are worth remembering however, The most important is that parentheses have the highest operator precedence. If you're not sure of a particular operator precedence issue you can enforce your own order of operations with parentheses and get along just fine. Another important one is the precedence of logical NOT AND & OR between themselves, these are frequently used in programs together, so it's useful to remember the precedence order. NOT has the highest, then AND, and the lowest is OR. NOT AND OR. The same applies to the bitwise NOT AND OR/XOR. One last precedence issue that might pop up semi-frequently is that bitwise AND has a lower precedence than the relational operators (namely the inequality operator). This is relevant for the example in the previous chapter of testing for the existence of bit flags. (Note the parentheses present in that example)

printl("beevus" || !true && "butthead"); // "beevus"
// !true is evaluated first, NOT has the highest precedence, it becomes false
// next is false && "butthead", which becomes false
// next is "beevus" || false, which finally evaluates to "beevus", which is then printed to console