Yichao, not long ago I had a similar question (it was in the context of
building a templating system), you were very kind and point me in the right
direction. So I kept digging.
Marius, sorry for piggy backing on your question, but I'm curious about
some code that seems to do the trick. I'm curious if I'm missing anything.
# A.jl
push!(LOAD_PATH, ".")
module A
using B
function a()
@injectvar
println("in a()")
@show external_var
end
a()
try
println("in A")
@show external_var
catch ex
@show ex
end
end
#B.jl
module B
export @injectvar
macro injectvar()
esc(:(external_var = 5))
end
end
If I run A.jl I get:
in a()
external_var = 5
in A
ex = UndefVarError(:external_var)
So external_var is defined in A.a() but not in A.
# C.jl
push!(LOAD_PATH, ".")
module C
using A
A.a()
try
println("in C")
@show external_var
catch ex
@show ex
end
end
Similarely, if I run C.jl I get
in a()
external_var = 5
in A
ex = UndefVarError(:external_var)
in a()
external_var = 5
in C
ex = UndefVarError(:external_var)
external_var is only available inside the function.
marți, 27 septembrie 2016, 14:36:48 UTC+2, Jussi Piitulainen a scris:
>
> You might be able to wrap your expression so as to create a function
> instead, and call the function with the values of the variables that the
> actual expression depends on. In Python, because I haven't learned to
> construct expressions in Julia yet and don't have the time to learn it now:
>
> def f(x): return eval("lambda x: x + 1")(x)
>
>
>
> tiistai 27. syyskuuta 2016 12.28.40 UTC+3 Marius Millea kirjoitti:
>>
>> Hi, is there a way to "eval" something in the current scope? My problem
>> is the following, I've written a macro that, inside the returned
>> expression, builds an expression which I need to eval. It looks like this,
>>
>> macro foo()
>> quote
>> ex = ...
>> eval_in_current_scope(ex)
>> end
>> end
>>
>> Now, you might say I'm using macros wrong and I should just be doing,
>>
>> macro foo()
>> ex = ...
>> end
>>
>>
>> but in this case when I build "ex", it needs to occur at runtime since it
>> depends on some things only available then. So is there any way to go about
>> this? Thanks.
>>
>>