const vs var

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By swipis
:warning: Old Version Published before Godot 3 was released.

Hi, sorry for stupid question, but what difference between var speed = 2 and const SPEED = 2? I tried to find on doc page, but no luck or maybe I missed.
Thank you!

:bust_in_silhouette: Reply From: atze

const defines a constant variable, once initialized the value can’t be changed Constant (computer programming) - Wikipedia
var defines a “normal” variable, the value can be changed at any time.

“constant variable”? A variable varies, otherwise it’s not variable.
Just pulling your leg. But the proper terme would be constant value, opposed to variable value.

Gokudomatic2 | 2016-04-03 17:26

I thought about that, too but then i decided to stick with the terminology the official documentation uses

atze | 2016-04-03 20:33

But using GDScript I can change the constant value any time and I don’t know why.
Constants are not very constant

gcivico | 2018-02-25 06:54

Why would I want an unchangeable variable?

PeteyGANG | 2020-08-26 01:07

Constants are helpful in a few ways.

Like a normal variable, you can use them to make your code more readable to others. You can also use them so that the value is defined once in the code and then used in multiple places, if you have to change the value later, then you only need to change one line of code.

Previously constants were used for speed as they did not require extra memory lookups at runtime to retrieve the value. It seems after a quick google search, this no longer seems to hold true for most languages. Not sure if they are faster or not in GDScript.

sabjian | 2020-10-23 18:26

:bust_in_silhouette: Reply From: glenneric1

If it’s anything like python then a constant
variable is shared among all instances.
Without constant each instance
gets it’s own copy to change.

To do that you need to autoload (in Project Setting>AutoLoad) a script with ‘Global Variable’ enabled, then you can access it with the name you set in the autoload tab.
For example: with an AutoLoad script named “Global” you would access it with that name as if it’s a variable accessing a node.
So in the AutoLoad script, you do var previous_health then when switching scenes you do Global.previous_health = health and in the other scene you start with health = Global.previous_health
Also, the above comment already answered the question over 3 years after you did.

IronStudios | 2022-03-04 22:51