Variable variables in Elixir

195 views
Skip to first unread message

eksperimental

unread,
Jul 14, 2016, 11:31:56 AM7/14/16
to elixir-l...@googlegroups.com
Hello list:

I'm trying to access variables via a list of atoms,

So given:
iex> a = 1
...> b = 2
...> c = 3
...> vars = [:a, :b, :c]

I would like to print the value in each variable
...> for var <- vars, do: IO.inspect(var)

How can I achieve this

I have tried this to no avail

iex> quote(do: var!(a)) |> Code.eval_quoted
** (CompileError) nofile:1: expected variable "a" to expand to an
existing variable or be part of a match (elixir) expanding macro:
Kernel.var!/1 nofile:1: (file)


thank you.

José Valim

unread,
Jul 14, 2016, 12:02:57 PM7/14/16
to elixir-l...@googlegroups.com
You need to pass your binding to eval quoted, see Kernel.binding/0. That will return all variables up to some point. However, you will also see binding is a keyword list, so you can simply get the variable value directly from it.



José Valim
Skype: jv.ptec
Founder and Director of R&D


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-talk/20160714223146.3fc22245.eksperimental%40autistici.org.
For more options, visit https://groups.google.com/d/optout.

eksperimental

unread,
Jul 14, 2016, 5:34:10 PM7/14/16
to elixir-l...@googlegroups.com
thank you Jose.
`binding()[:a]` is the way to go.

iex> a = 1
...> binding()[:a]
1

Just for the record of anybody in the list or Googling this, to achieve this with macros one can do:

iex> a = 1
...> quote(do: var!(unquote(Macro.var(:a, nil)))) |> Code.eval_quoted(binding) |> elem(0)
1

or simply
...> quote(do: var!(unquote({:a, [], nil}))) |> Code.eval_quoted(binding) |> elem(0)
1

if anybody else knows a simpler way, please let me know.


On Thu, 14 Jul 2016 18:02:34 +0200
José Valim <jose....@plataformatec.com.br> wrote:

> You need to pass your binding to eval quoted, see Kernel.binding/0.
> That will return all variables up to some point. However, you will
> also see binding is a keyword list, so you can simply get the
> variable value directly from it.
>
>
>
> *José Valim*
Reply all
Reply to author
Forward
0 new messages