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?
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?
You can't. Julia's
eval
always evaluates code the current module's scope, not your local scope. Callingeval
at run time is an anti-pattern and a performance killer.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:But my preferred method to evaluates an expression at run-time is to create a function, I think it's the most efficient:
Depending on the application, you could
eval
the entire function to get at the local value ofi
such as @simonster describes in this answer.