Julia Notes6 - Scope of Variables

global, local, hard, soft

Global

Each module introduces a new global scope, separate from the global scope of all other modules—there is no all-encompassing global scope.

Note that while variable bindings can be read externally, they can only be changed within the module to which they belong.

This demonstrates some important aspects of scope: in a scope, each variable can only have one meaning, and that meaning is determined regardless of the order of expressions.

Local

soft scope在REPL和file里有区别。

Let

跟javascript里var和let的区别类似。

An assignment modifies an existing value location, and let creates new locations. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures.

Loops and Comprehensions

这里的loops应该指for-loop, while不行需要自己用let做binding

In loops and comprehensions, new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a let block

outer,没有的话是0

julia> function f()
           i = 0
           for outer i = 1:3
               # empty
           end
           return i
       end;

julia> f()
3

Constants

性能优化

The const declaration should only be used in global scope on globals. Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary, and in fact are currently not supported.

Note that const only affects the variable binding;

修改const可能只是warning!

if a method references a constant and is already compiled before the constant is changed, then it might keep using the old value: