【发布时间】:2018-11-02 03:30:16
【问题描述】:
我正在尝试使用在代码块本身中定义的变量在引用块中调用私有宏。 这是显示我想做的伪代码(不起作用)
defmodule Foo do
defmacrop debug(msg) do
quote bind_quoted: [msg: msg], do: IO.puts(msg)
end
defmacro __using__(_) do
quote do
def hello do
my = "testme"
unquote(debug(quote do: my))
end
end
end
end
defmodule Bar do
use Foo
end
Bar.hello()
这会在编译时(在我看来)被转换为:
defmodule Bar do
def hello do
my = "testme"
IO.puts(my)
end
end
有什么方法可以实现吗?我正在努力寻找与之相关的任何文档。
更新
我发现:
defmodule Foo do
defmacrop debug() do
quote do: IO.puts("hello")
end
defmacro __using__(_) do
quote do
def hello do
my = "testme"
unquote(debug())
end
end
end
end
正确转换为我需要的,但我正在努力寻找一种按原样传递变量的方法,以便它变为IO.puts(my)
【问题讨论】:
标签: macros elixir metaprogramming