 |
 | | |
Variables | | |
|
Before we can discuss expressions, you should understand how variables work.
Variables represent locations in memory where data is stored.
For example, you can assign a number to some variable and then access or change it later.
As you hopefully learned from last chapter, we address each variable by its identifier or name.
As opposed to variables, numbers and strings in your code are technically referred to as "literal values" or simply "literals".
|
 |
"hey!" -- literal
62 -- literal
my_var -- variable
a = 5
-- a now equals 5
b = a
-- b now also equals 5
|
 | | |
Mathematical expressions | | |
|
High-level computer languages, such as Lua, can interpret mathematical expressions written in their "natural" form.
This means that you can write algebraic statement in the format you learned in school.
The compiler will figure out the correct precedence, computing multiplication before addition and so forth.
|
 |
-- some expression
a * -1 + 4 / 5 % 2
-- implied precedence
(a * (-1)) + ((4 / 5) % 2)
|
 | | |
| | |
|
The most important thing you should note about expressions is how they affect the values of the variables being used.
For example, the expression a plus b (a + b) gives you an outcome (in the form of another number) but a and b themselves remain the same.
So how do we go about changing the value of a variable?
The simplest way to do so is through what we call "assignment".
|
 |
|
 | | |
| | |
|
To change or assign a new value to a variable, you have to use the equal sign symbol (=).
For example, writing negative a (-a) will not affect the value of variable a.
To actually negate the variable, you have to use assignment through the syntax a equals negative a (a = -a).
-a -- not an assignment
a = -a -- assignment
-- assign the result of 1 + 2 to a
a = 1 + 2
-- add 2 to the current value of a
-- and assign the result to a
a = a + 2
|
 |
|
 | | |
Logical expressions | | |
|
Comparing factors belongs to another class of expressions, called "Boolean" or logical.
They work similarly to the mathematical expressions you're already familiar with.
The difference is that logical expressions give results that are not numbers, but Boolean values, either "true" or "false".
-- find the result of 2 > 5
-- and assign it to variable a
a = 2 > 5
-- variable a now equals false
|
 |
2 > 1 -- true
5 < (10 - 6) -- false
|
 | | |
|
Next: Program flow
|
 | | |
|
|