A type coercion is when, under certain conditions, Godot automatically converts ("casts") a type into another for convenience.
Type coercion is sometimes referred to as "implicit type casting" to differentiate it from "explicit type casting".
For example, if you do this:
var number := 10
number += 10.5
number
will be equal to 20
, not 20.5
, because the 10.5
float
will be implicitly cast to an int
. Godot will warn you: Narrowing conversion (float is converted to int and loses precision).
.
If we have a health value, and we show it in a string like so, the int
will be implicitly converted to a String
:
var health := 10
var health_text := "Your health is: %s"%[ health ]
The most often used type coercion to happen implictly is transforming values to true
or false
so that they can be used in if
or while
statements.
For example, if we wanted to do something only if the enemies
array is not empty, we could write this:
if enemies.size() > 0:
print("There are enemies!")
if enemies:
print("There are enemies!")
in the second example, the enemies
array is not empty, so the print
statement is executed.that's because empty arrays are coerced to false
, and non empty arrays to true
.
The rules that govern under which conditions values are coerced, and what they are coerced to, are language specific, complicated and not intuitive.
When it happens implicitly, type coercion can lead to unexpected behavior. Godot helpfully warns you in most cases, but we still recommend longer, explicit lines.
Consider the following example:
var wounded := false
if wounded:
speed = speed / 2
Assume a month later, you change the value of wounded
like so:
var wounded := 0.0
if wounded:
speed = speed / 2
Where wounded
increases from 0
to 1
over several hits, and you only want the character to look wounded when wounded
is over 0.5
.
Now the if wounded:
will return false
in the beginning, which is what we want. But it will return true
for anything over 0
, which is not the behavior we want.
The if
isn't correct anymore, but you will have to remember to change it yourself. Godot won't be able to help you.
But if, from the start, you had written:
var wounded := false
if wounded == true:
speed = speed / 2
When changing the wounded
variable to
var wounded := 0.0
Godot will say Invalid operands "float" and "bool" for "==" operator.
, and you will have to remember to handle the if
yourself.
Not using implicit coercion also helps other people that come from other languages with different rules.See Also
Related terms in the Glossary