Range Over Iterators in GDScript
With the provided input, the task is to translate the Go code example into GDScript. Here is how the code and explanation will look in Markdown format suitable for Hugo:
Starting with Godot version 3.2, GDScript has added support for iterators using the for
loop, which lets us range over pretty much anything!
extends Node
class List:
var head: Element = null
var tail: Element = null
class Element:
var next: Element = null
var val: Variant = null
func push(val: Variant) -> void:
if tail == null:
head = Element.new()
head.val = val
tail = head
else:
tail.next = Element.new()
tail.next.val = val
tail = tail.next
func all() -> Iterator:
return Iterator.new(self)
class Iterator:
var list: List
var current: Element
func _init(list: List) -> void:
self.list = list
self.current = list.head
func has_next() -> bool:
return self.current != null
func next() -> Variant:
val = self.current.val
self.current = self.current.next
return val
func _ready():
var lst = List.new()
lst.push(10)
lst.push(13)
lst.push(23)
for val in lst.all():
print(val)
# To iterate over Fibonacci numbers:
class Fibonacci:
var a: int = 1
var b: int = 1
func all() -> Iterator:
return Iterator.new(self)
class Iterator:
var fibonacci: Fibonacci
func _init(fibonacci: Fibonacci) -> void:
self.fibonacci = fibonacci
func has_next() -> bool:
return true
func next() -> int:
var a = self.fibonacci.a
var b = self.fibonacci.b
self.fibonacci.a = b
self.fibonacci.b = a + b
return a
func _ready():
var fib = Fibonacci.new()
for n in fib.all():
if n >= 10:
break
print(n)
GDScript’s for
loop ranges over iterators using the next()
method to get the next element until has_next()
returns false
. We implemented the List
class with a nested Element
and Iterator
class to handle iteration and the push
method to add elements to the list.
The Fibonacci
class generates an infinite sequence of Fibonacci numbers as long as the for
loop continues. This is illustrated with a break statement when the current number equals or exceeds 10.
To run this code, attach it to a Node in your Godot scene and run the scene.
By leveraging GDScript’s support for iterators, we can elegantly iterate over custom data structures like lists or even infinite sequences like Fibonacci numbers. This makes GDScript both powerful and expressive for game development in Godot.