Hi there. I have found some behavior of the “@eval”-macro that I cant quite explain.
So, as far as I understand it, “@eval expr” takes a segment of code, and evaluates it as if it had been written at that point in the sourcecode. But if “expr” mixes the global variable-scope with a local one, it seems to not work properly.
An example:
@eval begin
x=1;
x+=1
println(x)
end
println("this worked!")
This returns
2
this worked!
, as is expected. But if I write
@eval begin
x=1;
while x<2
x+=1
end
println(x)
end
println("This did not work!")
, then I get
UndefVarError: x not defined
Stacktrace:
[1] top-level scope at .\In[2]:4
[2] eval(::Module, ::Any) at .\boot.jl:330
It seems that the x in x+=1
in the scope of the while-loop is no longer recognized. The same happens with a for-loop instead of “while”.
If I just remove the “@eval” it works of course as intended
I can also fix this by encapsulating the x in its own scope:
@eval begin
let x=1
while x<2
x+=1
end
println(x)
end
end
println("This works again!")
this, again, results in
2
This works again!
As I see it, all three versions should return 2. Of course I can work around this, but I would like to know whether this is a bug, or, if not, why this happens.
Notes:
-I tried this with versions 1.2.0 and 1.3.1, in both a shell and a notebook, with identical results.
-this is not a purely artifical problem, but a reduced form of an error with my Script for data-evaluation. When I include(...)
that Script I run into exactly the same error, and include
- as i understand it - uses the eval-function on whatever is provided as an argument.