difference between initialising variables

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

what is the difference between these two initialisations?

var direction_with_equals = Vector2()
var direction_with_colon : Vector2
:bust_in_silhouette: Reply From: timothybrentwood

Both initialize the variables to Vector2(0,0). For direction_with_equals you can assign the variable to any Variant you like e.g. direction_with_equals = 5 is valid. For direction_with_colon you can only assign the variable to other Vector2 objects. direction_with_colon = 5 should give you an error in your editor at the very least and may give an error in the debugger when you run it.

var a := Vector2() is the same as direction_with_colon.

It’s not implemented right now but I think in godot 4 “typing” your variables with the colon ala direction_with_colon should give you performance increases.

:bust_in_silhouette: Reply From: Foreman21


For me,

This define the type of the variable as Vector2. It is static typing

var direction_with_colon : Vector2 # Define the type
... Some code
direction_with_equals = Vector2(3.0 , 1.0) # Initialize it.

In this case, the variable can only take the same type which was declared.

And this

var direction_with_equals = Vector2()

is dynamically typing the variable while his initialising. The variable will only take only the same type as defined.

If you want to prevent a wrong type of varible use static typing.

See Static typing in GDScript.

And in answer to your question:

I guess that for basic type like int string vector2d …
Static typing will also initialise it with a basic value, 0, “” , ( 0.0,0.0)

But with more complex type like PacketPeerUDP, it will not be initialized and will make and error.

Correct me if I wrong.

Regards, Forman21.