News

New paper!

Wednesday, March 25, 2020

Julia global and local scopes

A tricky feature I found in Julia is that loops (for & while) have 'local scope' within loops; you can't access global variables to update them inside loops!
For example,

This works

   function AddOne(x)
         x += 1;
   return x
   end;

   g = 0;
   x = 10;
   while g < 1000
         global g = AddOne(g);
   end;

If I remove global, an error appears "ERROR: UndefVarError: g not defined" (inside the loop).

Similarly, this does NOT work

   g = 0;
   while g < 100 # g in this line is a global variable
         g = 1000;  # g here is a local variable
   end;
This while loop doesn't stop. This seems to be because those two 'g's are different.

Whereas this works

   g = 0;
   while g < 100
         global g = 1000;
   end;
This while loop immediately stops by changing g from zero to 1000.


* Broadcasting for integer does not work
I used x += 1 above.
By contrast, operation with a period (e.g., ".+") is often used for a pairwise operation for elements in matrices.
Thus, you may be used to add a period for non-linear-algebraic operations.
[BUT the following does NOT work]
   x = 0;
   x .+= 0;
"ERROR: MethodError: no method matching copyto!(::Int64, ::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{0},Tuple{},typeof(+),Tuple{Int64,Int64}})"
Because ".+" has an aspect of broadcasting (for elements in matrix), this does not work for an integer variable.

[While this works]
   x = 0;
   x += 0;