All Questions


Velcro Nator

Colon after Variable

I am wondering the purpose of the colon after the variable in the code here. As it seems to work with

var velocity = Vector2.ZERO

var velocity: = Vector2.ZERO

var velocity: Vector2 = Vector2.Zero

Seems to be the same for the other variables as well.

I guess the last version tells you exactly what the variable is. Good for readability. I just curious about your thinking.

  • Nathan Lovato replied

    With the colons, variables become typed, so that here, the gdscript compiler will give you an error:

    var velocity: = Vector2.ZERO
    velocity = 3.0 

    When you just have the : =, the compiler will pick the variable's type based on the value you assign to it, here Vector2. We use this to save having to repeat the type:

    var character_name: = "Rudolph" # the type will be String
    var data: = [] # the type will be Array

    Typed code will generally prevent some bugs from happening, and with newer versions of Godot it will also greatly improve performances.

    Note that in Godot 3.1, the compiler has a hard time figuring out the type of nodes you get in your code. That's why in the course you may see something like:

    onready var anim_player: AnimationPlayer = get_node("AnimationPlayer")
  • N
    Velcro Nator replied

    Thanks for the quick answer. Nice that I was in the ball park.