Using Options in Nest Macro

Hi Everyone,

I am trying to access the options passed from a parent macro to child macro wiith the using macro and so far I am uncessfull. The parent macro can access the options passed but the child macro can not.

defmodule Nest do
defmacro using(opts) do
quote do
options = unquote(opts)
IO.inspect options

  defmacro __using__(_) do
    options = unquote(opts)

    quote do
      options = unquote(opts)
      ##I want to access opts here.....
    end

  end
end

end
end

In the first instance, opts is not defined in the __using__/1 macro so this code won’t compile.

Remember inside a quote block you are dealing with AST - compile time code - not runtime code. So there’s no lexical scope to for opts and no closure over the outer macro.

Its quite an unusual construct you’re building there so perhaps you’ll get better assistance if you also explain what you’re trying to achieve.

To help get you started, the follow compiles and runs. But it may not be what you are after:

defmodule Nest do
  defmacro using(opts) do
    quote do
      options = unquote(opts)
      IO.inspect options

      defmacro __using__(unquote(opts)) do
        options = unquote(opts)

        quote do
          IO.inspect unquote(options)
        end
      end
    end
  end
end

defmodule Nest.Test do
  require Nest

  Nest.using(a: :a)
end

Running:

kip@Kips-iMac-Pro thing % iex -S mix
Erlang/OTP 22 [erts-10.6] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [hipe]

Compiling 1 file (.ex)
[a: :a]
Interactive Elixir (1.10.0-rc.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>