Variables in GDScript

In GDScript, variables are dynamically typed, but you can optionally specify their types for stricter type checking.

extends Node

func _ready():
    # var declares a variable
    var a = "initial"
    print(a)

    # You can declare multiple variables at once
    var b = 1
    var c = 2
    print(b, " ", c)

    # GDScript infers the type of initialized variables
    var d = true
    print(d)

    # Variables declared without initialization are null
    var e
    print(e)

    # In GDScript, there's no special syntax for short declaration
    # You always use 'var' to declare variables
    var f = "apple"
    print(f)

To run this script in Godot:

  1. Create a new script and paste this code.
  2. Attach the script to a Node in your scene.
  3. Run the scene.

The output will be:

initial
1 2
true
null
apple

In GDScript:

  1. Variables are declared using the var keyword.
  2. You can optionally specify the type after the variable name, like var b: int = 1.
  3. Variables are dynamically typed by default, but you can enable type checking for stricter coding.
  4. Uninitialized variables are null by default.
  5. There’s no special syntax for short declaration - you always use var.
  6. GDScript uses print() for console output instead of a separate package.

GDScript is designed to be simple and easy to use, especially within the context of the Godot game engine. Its syntax is inspired by Python, making it quite different from statically typed languages.