Hey!,
I’m defining a macro that is expected to be called with a variable (provided by the user from their scope) and assign to it. I was expecting the anonymous function generated by the code bellow to be able to assign some value into this variable. I was thinking that since I’m unquoting the var explicitly that would make it unambiguous what variable I’m referring to (the user provided one) and not a new variable inside a new function scope.
May you help me get this right?
Thanks, :)`
defmodule FooTest do
use ExUnit.Case
defmacro foo(var) do
quote do
fn value ->
old = unquote(var)
unquote(var) = value
old
end
end
end
test "change the given var" do
x = 1
assert 1 == foo(x).(99)
assert x == 99 # Fails here, as x is still 1
end
end
Edit: Added another test without a macro, but in this case I understand the x
inside the anonymous function might actually be fresh-variable on the anon-fun-scope. Again, I’d expect the macro case to work as I’m not talking about a new x
but the original user provided one.
test "change the given var" do
x = 1
assert 1 == (fn y -> x = y; x end).(99)
assert x == 99 # also fails, but that's ok.
end