Can macros use variables defined by their caller?

Is there a way to have a macro use a variable defined outside of itself in the resultant AST that is generated?

Assume I want a “final” bit of code that looks something like this:

def foobar() do
  a = 1
  IO.puts a
end

Would it be possible to have the IO.puts call, or any other call, be generated by a macro?

A naive implementation looks like this

defmacro print_a() do
  quote do
    IO.puts a
  end
end

def foobar() do
  a = 1
  print_a()
end

But does not work, the compiler complains about undefined function. I don’t wish to override the value of the variable, I can use var! for that, but rather just use it in the generation of code.

1 Like

Check out the var!/2-macro.

4 Likes

Can’t believe I didn’t try it.

Thank you