How to make a custom datatype (something like a Vector4 class)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mcolpus

I want to create a class to hold some data. For the sake of the question, I want a Vector4 class. How would I build this with GDscript.
It seems that Custom Resources is the only method which has worked to an extent.

extends Resource
class_name Vector4 

export(float) var x = 0
export(float) var y = 0
export(float) var z = 0
export(float) var w = 0

func length():
    return sqrt(x*x + y*y + z*z + w*w)

This is all fine. But if I try to add a method to create a Vector4 from a Vector3 it gets errors about cyclic reference.

func from_v3(v: Vector3):
    return Vector4.new(v.x, v.y, v.z, 0)

This seems to be resolved if I use get_script(), but this wouldn’t work in a static factory method.
Is there a better method? Also being able to override equality, or do something like Vector4.Up would be nice.

Alternatively, I’ve seen some people use dicts for structs but that seems to lose a lot. Thanks

:bust_in_silhouette: Reply From: Calinou

You could use an inner class for this purpose.

Also, cyclic references will most likely be allowed in Godot 4.0 thanks to the GDScript rewrite.

Thanks.
To make the inner class accessible elsewhere I guess you can use class_name on the parent class?
4.0 sounds nice

mcolpus | 2020-07-05 17:31