使用注入值

时间:2016-09-22 13:53:20

标签: macros metaprogramming elixir

我尝试使用注入的值,如:

quote do
  var!(state) = "something"
  unquote(block)
  do_something_else_with(state)
end

我知道它是邪恶的,但我想这只是为了好玩。是否有可能在该块之后访问该状态可能会或可能没有对它做任何事情?

1 个答案:

答案 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"}