Introduction to the Julia programming language

9 Scope of Variables¶

In REPL, values are in Global scope¶

In [1]:
x = "Hello"

# "Functions", "for", "while", "try-catch-finally", "let"
# all introduce new scopes ("if" does not)

# Functions do not change variables in global scope
function f1()
    x = 3 # equivalent to "local x = 3"
    return x
end

f1(), x
(3, "Hello")
In [2]:
function f2()
    return x
end

f2()
"Hello"

If a function assigns a variable, that variable is never refering to a global variable implicitly

In [3]:
function f3()
    if randn() > 0
        x = 3
    end
    return x
end

# Never says "Hello", x is always local
f3()
UndefVarError: `x` not defined



Stacktrace:

 [1] f3()

   @ Main ~/uni/Vorlesungen/Julia-Course-Uni-HD/julia-09-scope.ipynb:5

 [2] top-level scope

   @ ~/uni/Vorlesungen/Julia-Course-Uni-HD/julia-09-scope.ipynb:9

Use global to explicitly use global variables

In [4]:
function f4()
    global x
    x = "Hello There"
end

f4(), x
("Hello There", "Hello There")

Variables are inherited from non-global scope!

In [11]:
function g1()
    function ginner()
        j = 2 # Try with and without "local"
        k = j + 1
    end
    j = 0
    k = 0
    return ginner(), j, k 
end

g1()
(3, 2, 3)

The scope is set by where the function or scope is introduced:

In [6]:
function gouter()
    j = 2
    k = j + 1
end

function g2()
    j = 0
    k = 0
    return gouter(), j, k
end

g2()
(3, 0, 0)

But the order does not matter!

In [7]:
even(n) = (n == 0) ? true : odd(n - 1)
even(10) # Odd is not defined at call time
UndefVarError: `odd` not defined



Stacktrace:

 [1] even(n::Int64)

   @ Main ~/uni/Vorlesungen/Julia-Course-Uni-HD/julia-09-scope.ipynb:1

 [2] top-level scope

   @ ~/uni/Vorlesungen/Julia-Course-Uni-HD/julia-09-scope.ipynb:2
In [8]:
odd(n) = (n == 0) ? false : even(n - 1)
# But here it is
even(1000)
true