Reputation: 924
In Julia, if we have a string set to a variable :
a = "hi"
and a function that has the same name as the value of the variable :
function hi()
return "hello"
end
can we like parse the variable and then run, or evaluate, the value in the string? If so , how could it be done using these example variable and function?
Upvotes: 3
Views: 1033
Reputation: 42214
You can do this in at least two ways:
julia> eval(Symbol(a))()
"hello"
or
julia> eval(Meta.parse(a*"()"))
"hello"
In the first way we create a Symbol
representing the function and a Julia Symbol
can be evaluated immediately. Once the symbol is parsed to a Julia object we call immediately the function (that is why there is a trailing ()
).
In the second example we parse the Julia code as a String
and then evaluate it.
A must-read is the meta-programming manual that can be found here: https://docs.julialang.org/en/v1/manual/metaprogramming/
Upvotes: 5