A boolean expression is any expression that produces one of two particular values called boolean values: true
or false
.
A boolean expression can result from a comparison or a function call. For example, the comparison 10 < 5
("Is 10 smaller than 5?") is a boolean expression. When the computer reads this, it runs the comparison and produces the value false
because 10
is not smaller than 5
.
Here are more examples of comparisons with numbers:
3 > 0
produces the value true
, because 3
is greater than 0
.
- '20 == 10
produces the value
false, because
20is not equal to
10`.
- '10 == 10
produces the value
true, because
10is equal to
10`.
We can make boolean expressions with any value type. For example, strings or vectors:
"hello" == "Hello"
produces the value false
because one of the two pieces of text starts with a capital letter and the other does not.
"Godot" == "Godot"
produces the value true
because both pieces of text are exactly the same.
Vector2(1,1) == Vector2(1,1)
produces the value true
because both vectors are the same.
All these examples use values directly (numbers, strings, vectors...), but you can use variables instead, as variables are a way to label a value:
var health = 3
if health == 0:
die()
Because health
has a value of 3
in this example, the boolean expression health == 0
("is health equal to 0
?") is equivalent to writing 3 == 0
. As the value of a variable can change, however, in practice, we can use variables to make dynamic comparisons.
Single and double equal signs are not the same operatorBe careful! The code 3 = 12
is not an expression. It will produce an error.In programming, a single equal sign (=
) is the assignment operator. This line of code says, "Put the value 12 in 3", which is not valid for the computer.It is different from the is equal to operator, which uses two equal signs (==
).Also, var my_name = "Alice"
is not an expression either. While the code is valid, this line does not produce a value. It assigns the value "Alice"
to the variable named my_name
.
Decimal numbers are impreciseWhat do you think the expression 0.3 * 3 == 0.9
will produce?In almost all programming languages, it will be false
!Decimal numbers ( float
in programming jargon, short for "floating-point numbers") are generally imprecise on the computer.Because of that, you cannot compare floats directly. Note that you can make comparisons like "larger than" or "smaller than". It's equality that causes problems.Most languages have functions to test if two decimal numbers are approximately equal, and Godot is no exception: it has a function named is_equal_approx()
for that: is_equal_approx(0.3 * 3, 0.9)
will return true
.
See Also
Related terms in the Glossary