I’m trying to build a statement for an if case within a function. Something like:
function build_string(test_value, comparator, value)
if eval(Meta.parse("test_value" * "comparator" * "value"))
[...]
end
… I get the error, that the parameters within the function are not known. As I already read, in the other topic, eval is only working globally and it should be avoided to use it within a function. However I’d like to get this to work. The only other option would be to make if cases which compares every possible value of the comparator parameter … but this would make the function huge.
eval evaluates the expression in the global scope of the containing module (cf. the documentation). You cannot use it in a function body like that. But you have noticed that yourself
If comp is a function, then simply do what @Sukera wrote below. If it is unavoidably a string (for whatever reason), a macro would make this work
macro comp_string(test, comp, val)
c = Meta.parse(comp)
:( $c($a, $b) )
end
@comp_string("A", "<=", "B")
true
function build_string(A, comp, B)
if @comp_string(A, comp, B)
[...]
end
I don’t think so - else there would be no need to Meta.parse a custom built string again (in the example they’re parsing test_value <= value, just without interpolating the comparator properly/having the proper syntax), only to evaluate the resulting expression.