Reputation: 11209
The following code fails with a meaningful error message.
x = 10
exp = quote
for i in 1:10
x = x + 1
end
x
end
eval(exp)
┌ Warning: Assignment to `x` in soft scope is ambiguous because a global variable by the same name exists: `x` will be treated as a new local. Disambiguate by using `local x` to suppress this warning or `global x` to assign to the existing global variable.
└ @ REPL[177]:3
ERROR: UndefVarError: x not defined
Stacktrace:
[1] top-level scope
@ ./REPL[177]:3
[2] eval
@ ./boot.jl:360 [inlined]
[3] eval(x::Expr)
@ Base.MainInclude ./client.jl:446
[4] top-level scope
Declaring the scope of x as local makes things work:
exp = quote
local x = 0
for i in 1:10
x = x + 1
end
x
end
eval(exp) # 10 as expected
This however does not work for some reason:
x = 0
exp = quote
global x
for i in 1:10
x = x + 1
end
x
end
eval(exp)
ERROR: UndefVarError: x not defined
Stacktrace:
[1] top-level scope
@ ./REPL[182]:4
[2] eval
@ ./boot.jl:360 [inlined]
[3] eval(x::Expr)
@ Base.MainInclude ./client.jl:446
[4] top-level scope
Upvotes: 1
Views: 287
Reputation: 42234
Change the location of global
:
julia> x=0;
julia> exp2 = quote
for i in 1:10
global x = x + 1
end
x
end;
julia> eval(exp2)
10
Upvotes: 1