In GDScript, a code block is a group of lines of code that are indented together. A block starts with a given indent level and ends on the next code line with a lower indent level.
Blocks of code can be nested within other blocks,
It's easier to understand with a picture, so here's an example of three nested blocks of code.
extends Node
var health := 10
func _ready() -> void:
print("we're in the function")
if health < 0:
print("we're in the if statement")
die()
print("we're out of the if statement and back in the function")
- The class scope, the widest scope, contains the
health
variable and the _ready()
function.
- The
_ready()
function scope contains the print("we're in the function")
line, the if
block, and the print("we're out of the if statement and back in the function")
line.
- The
if
block scope contains the print("we're in the if statement")
line and the die()
function call.
Blocks allow the computer to determine the scope of variables or the conditions under which some code should run.
Blocks can have different types of labels that are correct and incorrect.
For example, you cannot use print()
at the root level of a script, but you can use it inside a function. Contrary to that, you can use extends Node
at the root of a class, but not inside a function.
In most languages, blocks are defined by curly braces {}
, and indentation is optional. In GDScript, indentation is mandatory, and blocks are defined by the indentation level. People often call that type of language "whitespace significant" languages, but the technical term is "languages using the off-side rule".
In practice, curly braces languages and off-side rule languages are often written in the same manner.
if velocity.x != 0:
animated_sprite_2d.animation = "walk"
animated_sprite_2d.flip_v = false
animated_sprite_2d.flip_h = velocity.x < 0
elif velocity.y != 0:
animated_sprite_2d.animation = "up"
animated_sprite_2d.flip_v = velocity.y > 0
if (velocity.X != 0){
animatedSprite2D.Animation = "walk";
animatedSprite2D.FlipV = false;
animatedSprite2D.FlipH = velocity.X < 0;
}
else if (velocity.Y != 0){
animatedSprite2D.Animation = "up";
animatedSprite2D.FlipV = velocity.Y > 0;
}
Languages that use braces often have a style guide that recommends using the same indentation as GDScript. This makes it easier to read and understand the code. In practice therefore, there isn't much difference between the two types of languages.
GDScript usually has short lines of code, but sometimes you might want to split a long line into multiple lines. You can do that by using the backslash \
at the end of the line.
if health < 0 and \
coins > 0:
print("You're dead, but you have coins!")
To keep things organized, some people like to use parentheses ()
to group conditions.
if (health < 0 \
and coins > 0):
print("You're dead, but you have coins!")
You can use \
anyhwere to break lines.See Also
Related terms in the Glossary