Hey guys, if you haven’t read my other posts, I’ve been experimenting around with metaprogramming and macros. Recently I found out that Elixir doesn’t seem able to “see” a given variables value, even if it is explicitly provided in the source code:
a = 10
some_macro(a) # The variable will be used here
# => Inside the macro the variable will be seen as something like `{:a, [line: x], nil}`
Essentially all variables are all seen as nil
. I was hoping that Elixir could somehow see the value when the variable is explicitly bound in the code (seeing the value from dynamically passed variables — like in function parameters — would be a different story).
I looked at Macro.var/2
but it doesn’t seem to do what I want.
var(var, context)
var(var, context) :: {var, , context} when var: atom, context: atom
Generates an AST node representing the variable given by the atoms var and context.
Examples
In order to build a variable, a context is expected. Most of the times, in order to preserve hygiene, the context must be MODULE:
iex> Macro.var(:foo, MODULE)
{:foo, , MODULE}
However, if there is a need to access the user variable, nil can be given:
iex> Macro.var(:foo, nil)
{:foo, , nil}
Is there an actual way to achieve this? If not, why so? Is this a limitation of Elixir or is it a side effect from a certain feature/design decision?
EDIT:
I assume receiving a list as a parameter in a macro my_macro(args), do: IO.puts length(args)
and having it output the length of args
during compilation is not possible?