-
Notifications
You must be signed in to change notification settings - Fork 26
/
2_scoping.jl
91 lines (64 loc) · 1.18 KB
/
2_scoping.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# Julia docs: https://docs.julialang.org/en/latest/manual/variables-and-scoping/
x = 42
function f()
y = x + 3 # equivalent to `local y = x + 3`
@show y
end
f()
y
# x is global whereas y is local (to the function f)
# we can create a global variables from a local scope
# but we must be explicit about it.
function g()
global y = x + 3
@show y
end
g()
y
# we ALWAYS need to be explicit when writing to globals from a local scope:
function h()
x = x + 3
@show x
end
h()
function h2()
global x = x + 3
@show x
end
h2()
# This fact can lead to subtle somewhat unintuitive errors:
a = 0
for i in 1:10
a += 1
end
# Note that if we do not use global scope, everything is simple and intuitive:
function k()
a = 0
for i in 1:10
a += 1
end
a
end
k()
# Variables are inherited from non-global scope
function nested()
function inner()
# Try with and without "local"
j = 2
k = j + 1
end
j = 0
k = 0
return inner(), j, k
end
nested()
function inner()
j = 2 # Try with and without "local"
k = j + 1
end
function nested()
j = 0
k = 0
return inner(), j, k
end
nested()