引用表达式中的 Julia 全局变量抛出 UndefVarError

Julia global variable in quote expression throws UndefVarError

以下代码失败并显示有意义的错误消息。

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

将 x 的范围声明为本地使事情起作用:

exp = quote
          local x = 0
          for i in 1:10
              x = x + 1
          end
          x
      end
eval(exp)   # 10 as expected
      

但是由于某些原因这不起作用:

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

更改 global 的位置:

julia> x=0;

julia> exp2 = quote
                 for i in 1:10
                     global x = x + 1
                 end
                 x
             end;

julia> eval(exp2)
10