Undefined variable Error in a quote block

Hi all,

I was designing a macro and the code below is the return line of the macro, but it reports “i not defined”, I think it happens at $(result[i]) because once I replace it with other expr it is fine, so is there a way to correctly use a index on a vector in a quote block?

return quote 
          for i in eachindex($result)
          $v = $vect 

Thank you.

What $(result[i]) does is evaluate result[i] outside the quote expression inside the macro body, and then interpolate the value into the expression. result existed there but i didn’t, hence the error. $result[i] or $(result)[i] interpolate the result variable only.

Without the full macro I can’t really say this definitively, but the way you’re interpolating also seems problematic. One possible problem is the repeated interpolation. If you’re interpolating a non-expression, it’ll interpolate the same instance, which seems to be your intention; if you’re interpolating an expression, it’ll be evaluated to different instances:

julia> macro blah() vect = [1];    :($vect === $vect) end; @blah
julia> macro blah() vect = :([1]); :($vect === $vect) end; @blah

A more probable problem is interpolating something to the left side of an assignment. How did that not error in your case?

julia> macro blah2(x) v = 1; :($v = $x) end; @blah2(2)
ERROR: syntax: invalid assignment location "1"