All programmers know about the “if” statement. It would probably be the first conditional logic new coders learn, and the most widely used statement in programming. But what really represents TRUE ?
Godots IF statement can be used for more than simple boolean check.
Consider this statement.
if player_inventory:
show_inventory_ui()
This will return different values depending what ‘player_inventory’ really is. Is an integer TRUE? What about an empty array, or a color?
GDScript follows Pythons “thruthiness” model so all the below will return FALSE
if [] - empty arrays
if {} - empty dictionaries
if "" - empty strings
if null - null reference
if Vector2.ZERO and Vector2(0,0) - zero vectors
if Vector3.ZERO and Vector3(0,0,0) - zero vectors
if Vector4.ZERO and Vector4(0,0,0,0) - zero vectors
if Color(0,0,0,1) - opaque black only ( all other colors are TRUE)
if Color.BLACK - same as above
if 0 - Zero as integer
if 0.0 - Zero as float
if false: - false value
In our “player_inventory” example, if “player_inventory” is set to any of the above, their TRUE code statement will not run.
Godot also uses lazy ELIF structure which imporves writing clean and readable code.
if player_health <= 0:
player.die()
elif player_health >= 1 and player_health <= 50:
print("player health getting low +str(player_health))
elif player_health >= 51 and player_health <= 100:
print("player health is OK" +str(player_health))
The beauty in this is that the lazy structure means that if any of the statements return TRUE, the entire code block will be exited. In the above example, if “player_health” is equal or less than 0, the player_die() will run then the rest of the code block will not run.
The key takeaway is that “empty” or “zero” values evaluate to false, while anything with meaningful content evaluates to true. This pattern creates more readable code –
if player_inventory:
is immediately understood as “if the player has items,” while
if player_inventory != null and len(player_inventory) > 0:
clutters the logic with unnecessary details.
Combined with GDScript’s lazy evaluation in elif chains, these truthiness rules enable developers to write performant conditional logic that exits early when conditions are met. This not only improves code readability but also prevents unnecessary computations in complex decision trees.
Leave a comment