When I ran the Julia code below, there was an error: "UndefVarError: globalOptiValue not defined...". I thought that the globalValue is a global variable, but it is not. Thus, if I add the command "global globalValue" inside the for loop, my code will work. So, could anyone please have a look at it let me know what happened? Thanks in advance!
globalValue = 1.0;
tempValue = 0.1;
for ii = 1:10
# global globalValue; if I add this command, my code will work
tempValue = 5.0;## I have a function to update "tempValue"
if globalValue < tempValue
globalValue = tempValue;
end
end
It seems you are on Julia >= 0.7, where the scoping rules have changed.
Long story short, in a local scope, such as your for-loop, global variables are only inherited for reading but not for writing. There are two ways around it:
global
in front of the assignment (what you figured out yourself)let ... end
block (globalValue
isn't really a global variable anymore)In your case, the second option would look like
You can find more information here:
Although I find this a bit annoying myself, there are good reasons for why the change has been made. Also, on should try to avoid changing globals anyway. Let me quote the manual here (see link above):