How to pass variable into loop?

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.

a = 10
for i in 1:100
  global a
  b = a*2
  a = b*0.1
end

Or, as a puzzle for you:

julia> let
         a = 10
         for i in 1:1
           b = a*2
           a = b*0.1
           println(b)
           println(a)
         end
       end
20
2.0

julia> a
10

I admit, the documentation
https://docs.julialang.org/en/v1.3-dev/manual/variables-and-scoping/#Local-Scope-1
could be clearer. I am somehow now used to this behaviour but the documentation is not easy to digest.

Lots of deep thoughts about it:


and other threads.

I wouldn’t call it a debacle, actually I like it as it is or better: I like some of implications of it, e.g. one has to think about scope.

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.

1 Like