How can I eval a local variable in Julia

后端 未结 4 1144
太阳男子
太阳男子 2020-12-10 04:00
i = 50
function test()
  i = 10
  eval(:i)
end
test()  # => 50

Why does this evaluate to the global i instead of the local one? Is

4条回答
  •  再見小時候
    2020-12-10 04:35

    As @StefanKarpinski mentioned eval always evaluates in global scope, but if one really wants to evaluate something locally, there are various way to do it:

    import Base.Cartesian.lreplace
    i = 50
    function test1(expr)
      i=10
      eval(lreplace(expr,:i,i))
    end
    
    i = 50
    function test2()
      i = 10
      @eval $i
    end
    test1(:(i))  # => 10
    test2()      # => 10
    

    But my preferred method to evaluates an expression at run-time is to create a function, I think it's the most efficient:

    exprtoeval=:(x*x)
    @eval f(x)=$exprtoeval
    f(4) # => 16
    

提交回复
热议问题