See all glossary terms

Variable


title: Variable seeAlso:
  • constant
  • data
  • state
  • property
  • scope
  • language_identifier

The exact definition of a variable in computing is close to how they're used in mathematics, but not exactly the same.
In maths, you might write let x be 10.
In GDSCript, you would write:
var x = 10
Contrary to maths, the value assigned to x can be changed throughout the lifetime of the program, at runtime.
For example, later, you might write:
x = 20
To change the value to 20. The equivalent to Maths variables are more often called constants in programming languages, because they cannot change.
The act of writing var <name> is called a "variable declaration". It tells GDScript you will now use that name to refer to a specific value.
A variable can be written without a value:
var age
In which case, the value of the variable age is null (nothing) by default.
Later, you can assign a value to the variable:
func _ready() -> void:
	age = 20
Here, you assigned the value 20 to the variable age. This is like appending a label called "x" to the value 20; or, some people say they put the value 20 in a box called age.
For convenience, you can declare a variable with a value directly:
var age = 20
You can also specify the type of the variable:
var age: int = 10
In this example only allow values of type int will be allowed to be assigned to the variable. For convenience, GDScript allows us to skip writing the type explicitly when it can infer the type:
var age := 10
In this example, the variable age will be of type int too, because Godot can guess the type.

Anatomy of a variable

Variables must be named with a valid identifier. Identifiers in GDScript:
  1. start with a letter
  2. have no spaces and no special characters, except _, which is allowed

Parameters, Properties, Variables

  • Parameters are variables passed to a function
  • Properties are variables that are declared in the script root and accessible from outside the script.
Both obey the same rules as variables, and it is possible to use the word variable to refer to them.

Variable Scope

Variables are scoped; that means a variable is only accessible in the area where it's defined.
For example, the Player script below uses 2 variables: health and amount.
var health := 10

func take_damage(amount) -> void:
	health -= amount
While health is accessible to every function in the script, the parameter amount is only accessible in the function take_damage().
health is also accessible to other scripts as a member variable; other script can use player.health to assign it or read it.