Issue with loop


#1

Hi,

I need some help please, I have an error that i don’t understand how to fix it. Something that i can’t see.

julia> a=0
0

julia> (a+=1 for i in 1:3)
Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##3#4"))}(getfield(Main, Symbol("##3#4"))(), 1:3)

julia> a
0

julia> for i=1:3
a = a+1
end
ERROR: UndefVarError: a not defined
Stacktrace:
[1] top-level scope at .\REPL[4]:2 [inlined]
[2] top-level scope at .\none:0

Can someone help me to understand what is wrong?


#2

In order to modify a global in a loop you must write global a.


#3

Thank you in this case how can we write the loop in one line:

(global a+=1 for i in 1:3) does not work. any idea?


#4

The problem is that (global a+=1 for i in 1:3) creates a “generator” which goes through the loop lazily, ie at a later point when you call collect or iterate through it. You can just do [global a+=1 for i in 1:3] to run the loop immediately.


#5

Yes but this one is createing an array.

I found this way:

a=0
for i=1:3
eval(: (a+=1))
end


#6

use foreach


#7

I don’t think there’s any reason to use eval here. If you do what @StefanKarpinski suggested above:

a = 0
for i = 1:3
  global a += 1
end

you get what (I think) you’re looking for.


#8

Also note, if you don’t like using global you can just put this all in a function and it works:

function suma()
   a = 0
   for i = 1:3 
       a += 1
   end
   return a
end

#9

Along the lines @isaacsas suggestion, here is my temporary suggestion:

  • Use Jupyter for most interactive use for now
  • When you are in the REPL or in a julia script, never use loops or control structures relying on scope rules outside of a function. This will not be a major inconvenience in the short-term.

If you do this, the scoping behavior will be exactly the sort of thing you have in mind (i.e., you won’t need to think about global scope issues, never need to type global under normal circumstances, and can copy/paste code between functions and jupyter).

Finally, have faith that some variation of Another possible solution to the global scope debacle will be implemented when it is ready and tested, then you can start using loops again outside of functions/jupyter, and you probably won’t need to think about this stuff again.