I want to make a macro to substitute a long expression used in several functions to improve code readability. Each function has the same name for a certain argument, which is used in the macro, but when compiling the function Julia says the variable used in the macro is undefined even when escaped. Minimal example:
julia> macro mtest()
esc(x)
end
@mtest (macro with 1 method)
julia> ftest(x) = @mtest
ERROR: UnderVarError: x not defined
Now it gets weird:
julia> x = 1
1
julia> @mtest
1
julia> ftest(x) = @mtest
ftest (generic function with 1 method)
julia> ftest(2)
1
Why doesn't this function definition simply evaluate to ftest(x) = x
? How can I tell the macro to use the x
from the scope of the calling function rather than from the REPL? I want to use a macro to simply substitute a literal block of text, as in the C library I am using:
#define CHECK_STUFF \
big \
complicated \
expression \
involving x;
void func(x, y, z) {
//stuff
CHECK_STUFF
//more stuff
}
In this case CHECK_STUFF
must be macro, not a function, because it contains a goto
to a label in func
. My task is to translate this to Julia.