Struct Embedding in GDScript
GDScript supports composition through inheritance and inner classes, which can be used to achieve similar functionality to struct embedding in other languages. Here’s an example demonstrating this concept:
In this GDScript example:
We define a
Base
class with anum
property and adescribe
method.We then define a
Container
class that has aBase
instance as a property, along with its ownstr
property.In the
_ready
function (which is called when the node is added to the scene), we create an instance ofContainer
.We can access the base’s fields through the
base
property ofContainer
.The
Container
class has its owndescribe
method that calls thebase.describe
method, demonstrating method forwarding.GDScript doesn’t have interfaces, but we can use duck typing to achieve similar functionality. Any object that has a
describe
method can be used where a “describer” is expected.
To run this script:
- Create a new script in Godot and paste this code.
- Attach the script to a Node in your scene.
- Run the scene.
The output will be similar to:
This example demonstrates how GDScript can use composition and method forwarding to achieve functionality similar to struct embedding in other languages.