Where to define variables

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CollyBlargle
func _process(delta)
  var i = 0
  i += 1

vs

var i = 0
func _process(delta)
  i += 1

I have the option of declaring my variables wherever I want, but why should I ever not declare them at the top? Isn’t it unnecessary to declare variables twice in functions that run more than once?

Just as a mostly unrelated tip, I recommend avoiding duplicating the names of member variables (also called globals sometimes [debatable in this specific context], those defined outside a function) from those inside functions (local). One rudimentary example: a Polygon2D implementation with a sides member variable should not use the explicit variable name sides in any of its functions, unless you explicitly intend to modify the value associated with the member variable of the same name.
I used to frequently use the same variable name for my function arguments in their definitions as member variables used elsewhere by the same object, which eventually (not right away!) caused debugging issues. If you really want to use the same word for a local variable and a global, consider prepending a local_ to the local variable to differentiate it.

DDoop | 2020-07-06 23:44

:bust_in_silhouette: Reply From: Calinou

These are different. In the first code snippet, you’re creating a local variable i and incrementing it every time _process() is called. It will always be 1 when _process() is done running because it will be set to 0 again at the beginning of _process().

In the second code snippet, you’re creating a member variable i and incrementing it every time _process() is called. It will keep the previous value when entering _process(), which means i will be incremented by 1 every time _process() is run.

When declaring local variables, it’s recommended to declare them as close as possible to their first use to improve readability. On the other hand, you should keep member variables at the top of the script so they can be found more easily.