Small doubt in basic gdscript

I have good experience in C++, now I’m learning gdscript basics,

why the below code gives error when I increase value after the declaration of an variable current_speed outside the functions

extends Node2D
var current_speed = 300
current_speed += 35
func _ready():
print(current_speed)

but when I increase value of variable inside the buildin _ready fucntion, It gives output,

extends Node2D
var current_speed = 300
func _ready():
current_speed += 35
print(current_speed)

did I increase the value of an variable inside the functions like _ready() or _process(), why I can’t increase the value outisde of the functions
please tell , I am beginner, I will understand
thanks in advance

The only things you can do at toplevel (that is, not inside a function or nested class) are:

  • Set the name of the class: class_name Foo
  • Tell the class to inherit from something else: extends Node
  • Declare things (variables, functions, signals, etc.)

If you know how to read a formal grammar for a programming language, you can see more details here.

If you want to run code immediately when the game starts, do it in the _ready function.

1 Like

Thank you :slight_smile: