For in GDScript
GDScript, being a scripting language for the Godot game engine, has some differences in syntax and functionality compared to compiled languages. However, we can demonstrate similar looping concepts.
extends Node
func _ready():
# The most basic type, with a single condition.
var i = 1
while i <= 3:
print(i)
i += 1
# A classic initial/condition/after loop.
for j in range(3):
print(j)
# Another way of accomplishing the basic "do this N times" iteration.
for i in range(3):
print("range", i)
# While without a condition will loop repeatedly
# until you break out of the loop or return from
# the enclosing function.
while true:
print("loop")
break
# You can also continue to the next iteration of the loop.
for n in range(6):
if n % 2 == 0:
continue
print(n)In GDScript:
- We use
whileloops for condition-based iteration. - The
forloop in GDScript is used primarily for iterating over ranges or collections. - There’s no direct equivalent to Go’s
forwithout conditions, but we can usewhile truewith abreakstatement to achieve similar behavior. - The
continuestatement works similarly to Go, allowing you to skip to the next iteration.
To run this script in Godot:
- Create a new scene with a Node.
- Attach this script to the Node.
- Run the scene.
The output would be:
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5GDScript’s looping constructs are somewhat different from Go’s, but they can accomplish similar tasks. The for loop in GDScript is more akin to Python’s, primarily used for iterating over ranges or collections. For more complex looping scenarios, you might need to combine for loops with range() or use while loops.
Comments powered by Disqus