
A variable is a concept in mathematics and programming that refers to a "container" for data such as numbers or characters, or a "value that changes."
In Godot, you declare a variable as follows:
var [variable name] = [data to assign]:
Let's look at this by the type of data assigned.
Numbers
var number = 8
Strings
var word = "godot"
For strings, enclose the text in double quotes (" ").
Arrays
var arr = [0, 1, 2]
Dictionaries
var dic = "White": 50, "Yellow": 75, "Orange": 100
Nodes
var score_label = $CanvasLayer/ScoreLabel
For nodes, write the path where the file is located after the $ symbol.
Declared variables can be overwritten with different values later; conversely, if you do not want to change the value at all, use a constant.
Constants are declared by writing const before the variable name.
const number = 8
Variables can be declared at the beginning of a script or inside a function. Variables written at the beginning of a script are called global variables, and variables written inside a function are called local variables. The scope changes depending on where they are declared.
What is scope?
It refers to the "valid range" where a variable can be used.
Variables written at the beginning of a script can be used by all functions within that script.
Variables written inside a function are deleted the moment that function's processing finishes. Therefore, if you try to use that variable from another function, it cannot be found, resulting in an error.
1. Global variables
2. Local variables
3. An error occurs because you are trying to call a variable outside the scope of the local function.
Why write variables inside functions if there are restrictions?
You might think that if all functions could use variables, global variables would be enough, but there are three benefits to writing variables inside functions.
The first is improved safety (bug prevention). Since variables can have their values rewritten, this prevents risks such as having a variable with the same name changed arbitrarily by another function.
The second is reduced stress in naming variables. If a common variable name like 'result' is processed within a function, you don't need to worry about whether the variable name conflicts with other processes.
The third is memory savings. Local variables are discarded from memory the moment their processing ends. Compared to global variables that are kept in memory for the entire program, this reduces memory consumption.
In this article, I explained the basics of variables and scope. Next time, I plan to talk about variables in a bit more detail, such as type specification and annotations.
I will continue to share useful Godot features and tips. Please be sure to follow and like!
Thank you for reading until the end. See you in the next article.