Hello,
I have created some variable in the mainstream of a Julia stream; in order to pass them (to be modified) inside a for loop, I first declared them as global.
For instance;
global a = 10
for i in 1:100
b = a*2
a = b*0.1
end
give the error: UndefvarError: a is not defined
If I define global inside the loop as well, I get:
global a = 10
for i in 1:100
b = global a*2
a = b*0.1
end
> syntax: invalid syntax in "global" declaration
if I define the variable as global before giving any value, I still get the undefined error:
global a = Int8[]
a = 10
for i in 1:100
b = a*2
a = b*0.1
end
> UndefVarError: a not defined
I am still confused on how to pass values from the main to the loops in Julia. Any help, please?
Thank you.
When you are getting started, the easiest thing to do is work in jupyter for interactive “scripts”, and put things inside of functions when you are working in atom or the REPL. If you do that, it will work intuitively, and you don’t need global.
If you ever have to type global at that point, then you should probably rethink your code structure
Thank you. This is a bit counter-intuitive: I am used to declare the variables a global at the beginning and going into the loops. Here they are declared global INSIDE the loop and AFTER they have been assigned. Anyway I’ll treasure the tip for the next scripts!
I wouldn’t think of it that way. The variable is automatically global if you define it in the REPL outside a function. You just need to use the global keyword to modify a global in a loop.
For example,
julia> a = 10
10
julia> for i in 1:100
b = a*2
a = b*0.1
end
ERROR: UndefVarError: a not defined
Stacktrace:
[1] top-level scope at ./REPL[117]:2 [inlined]
[2] top-level scope at ./none:0
julia> for i in 1:100
b = a*2
global a = b*0.1
end
If you use functions or jupyter you won’t have to worry about this.