The for
, while
, and try
blocks (but not the if
blocks) all introduce a new scope. Variables defined in these blocks are only known to that scope. This is called the local scope, and nested blocks can introduce several levels of local scope.
Variables with the same name in different scopes can safely be used simultaneously. If a variable exists both in global (that is top level) and local scope, you can distinguish between which one you want to use by prefixing them with the global
or local
keyword:
The following example will clarify this as follows:
# code in Chapter 4\scope.jl
x = 9
function funscope(n)
x = 0 # x is in the local scope of the function
for i = 1:n
local x # x is local to the for loop
x = i + 1
if (x == 7)
println("This...