我尝试使用注入的值,如:
quote do
var!(state) = "something"
unquote(block)
do_something_else_with(state)
end
我知道它是邪恶的,但我想这只是为了好玩。是否有可能在该块之后访问该状态可能会或可能没有对它做任何事情?
答案 0 :(得分:2)
是的,但阻止和do_something_else_with
都需要始终使用var!(state)
,以便宏观卫生最终不会在结果代码中为state
提供不同的名称。这是一个例子:
defmodule Main do
defmacro with_state(do: block) do
quote do
var!(state) = "something"
IO.inspect {:before, var!(state)}
unquote(block)
IO.inspect {:after, var!(state)}
end
end
def main do
with_state do
IO.inspect {:inside_before, var!(state)}
var!(state) = "else"
IO.inspect {:inside_after, var!(state)}
end
end
end
Main.main
输出:
{:before, "something"}
{:inside_before, "something"}
{:inside_after, "else"}
{:after, "else"}