Julia - UndefVarError in macro when used in function but not in REPL -


i want make macro substitute long expression used in several functions improve code readability. each function has same name argument, used in macro, when compiling function julia says variable used in macro undefined when escaped. minimal example:

julia> macro mtest()     esc(x) end @mtest (macro 1 method)  julia> ftest(x) = @mtest error: undervarerror: x not defined 

now gets weird:

julia> x = 1 1 julia> @mtest 1 julia> ftest(x) = @mtest ftest (generic function 1 method) julia> ftest(2) 1 

why doesn't function definition evaluate ftest(x) = x? how can tell macro use x scope of calling function rather repl? want use macro substitute literal block of text, in c library using:

#define check_stuff \     big \     complicated \     expression \     involving x;  void func(x, y, z) {     //stuff     check_stuff     //more stuff } 

in case check_stuff must macro, not function, because contains goto label in func. task translate julia.

your macro computes value, not expression. thus, since macros run @ compile time , not @ runtime, esc(x) @ compile time but, since x 1 @ compile time, function compile f(x)=1. want instead have macro return expression x way function compiles f(x)=x. is:

macro mtest()     quote         x     end end 

will work. while have :x, syntax scales nicely.

in fact, tend program macros in "quote later" way. can first write macro , test in repl without returning expression , instead returning value. that's did here. it's easier working. however, useful in function, has return expression. easiest way showed: take had , put quote end around it. now, if had arguments macro need modify expression way interpolate values correctly. if general algorithm worked, part won't difficult (and have left trail of breadcrumbs how interpolate many odd things on so, search around if want interpolate weird stuff).


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -