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
. Variables in programming are different from variables in algebra, which represent unknown values.
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 "age" to the value 20
; or, as some people say, putting 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 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.
Variables must be named with a valid identifier. Identifiers in GDScript:
- start with a letter
- have no spaces and no special characters, except
_
, which is allowed
- 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.
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 scripts can use player.health
to assign it or read it.See Also
Related terms in the Glossary