How can I eval a local variable in Julia

2019-01-24 09:19发布

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 there a way to make it evaluate to the local?

标签: julia-lang
3条回答
神经病院院长
2楼-- · 2019-01-24 09:38

You can't. Julia's eval always evaluates code the current module's scope, not your local scope. Calling eval at run time is an anti-pattern and a performance killer.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-24 09:45

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
查看更多
The star\"
4楼-- · 2019-01-24 09:56

Depending on the application, you could eval the entire function to get at the local value of i such as @simonster describes in this answer.

查看更多
登录 后发表回答