Getting the arguments of the current function / visible variables

Let’s suppose I have a function that I do not know the arguments to. How could I go about obtaining the names and values of the arguments given to the function (when running inside it)?

For example:

def foo(a, b) do
  vars = magically_get_vars(...)
end

When called as foo(1, 2), vars would be set to a mapping such as [a: 1, b: 2].

I know that with __ENV__.vars I can get the names of the visible variables (which is fine too), but it does not contain the values. How do I obtain the values as well?

The real use case is an EEx layout that has no knowledge of the arguments passed to it but must pass those arguments on (this has to do with Raxx layouts and views). But I figured getting an answer to this more generic question would be interesting as well.

2 Likes

binding(context \ nil)

Returns the binding for the given context as a keyword list.

In the returned result, keys are variable names and values are the corresponding variable values.

If the given context is nil (by default it is), the binding for the current context is returned.

https://hexdocs.pm/elixir/Kernel.html#binding/1

def foo(a, b) do
  vars = binding()
end
5 Likes

And there it is! I knew I was missing something obvious, this is why you should go to bed early and sleep properly kids! :slight_smile: Thanks a lot!

1 Like