This is because global and local scopes. Is common feature in most programming languages.
You have defined num at the begginning of the code with
export (int) var num… it is defined “globally” and you can use it inside every function of your script. So, when you change its value with
num = 5 you are changing the value of that global value, and it won’t change again unless you explicity change it with another assignation like
num = 1.
However, in the second way, when you use
var num = 5 You are NOT using the global variable, you are defining a new variable with the same name inside the local scope of the function
_process (var is used to define variables). So when you do
var num = 5 you get a new variable named num with value of 5, different from global variable num. Inside
_process when you use num, you will be using local variable instead of global variable. But when you exit
_processfunction, local variables are removed, and you only keep your global variable with its original value. So when you stop pressing the button, the next time you enter process you wont be difining the local variable and you will be accessing global variable.
I don’t know if i made myself clear, please tell me if you don’t understand.
If you are familiar with other programming languages, tell me and i can see if i find a similar case for a better explanation.
is it just for _process function or every function i defined?
I am kind of familiar with python
mr.brown | 2019-01-19 15:15
Every function has its local scope. If inside a function a local variable (i.e. defined inside the function) has the same name than a global variable (defined outside functions), the variable used will be the local one. But this only affects inside that function!
I python, every variable you use inside a function must be defined in local scope. If you want to use a global variable you must use global keyword.
This will print 2 first for the print inside foo, and then 1 because outside function it will be using global variable.
This should print 2 twice, as global variable is modified inside function.
The first code snippet i share here would be similar to the code where you uses
var num=5, as you are defining the local variable. The second snipet is similar to the other case.
I edited previous comment to add python exampme
I understand now, thanks for answering
mr.brown | 2019-01-19 16:15
You are welcome! You may select the answer so others see it is solved.