O'Reilly logo

Learning Elixir by Kenny Ballou

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Context and macro hygiene

Since macros are about injecting code, special care must be taken for the context, of both the caller and the context of the macro. The injected code of the macro cannot safely assume that certain variables will be available for it to consume. For example, let's look at a macro definition that attempts to access some variables of the caller context:

defmodule ContextInfo do
  defmacro grab_caller_context do
    quote do
      IO.puts x
    end
  end
end

Load up this module in iex:

iex(1)> c "context.exs"
[ContextInfo]
iex(2)> import ContextInfo
nil
iex(3)> x = 42
42
iex(4)> grab_caller_context
** (CompileError) iex:4: undefined function x/0
    expanding macro: ContextInfo.grab_caller_context/0
    iex:4: (file)

After importing and binding a variable, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required