1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a bunch! But why does it work with local?
These two do very different things. local introduces a new local variable in the code block that you created. global tells how to use a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.