[erlang-questions] Generating a variable in a macro
Richard Carlsson
richardc@REDACTED
Tue Jan 9 13:11:26 CET 2007
Joel Reymont wrote:
> Is there a way to "auto-generate" a variable in a macro ala (gensym)
> in Lisp?
> [...]
> Unless I pass Any1, Any2, etc. into the macro, erl will complain that
> the use of Any is unsafe. Any workarounds apart from passing the
> error variable as a macro argument?
The standard trick is to wrap the macro body in a fun-application,
i.e.:
((fun () -> ...body... end)())
this keeps new variables in the body from being exported into the
surrounding environment. To avoid collisions between local variables
and existing variables in the environment, it is a good idea to
prefix all local variables with e.g., "__" or similar, as in:
-define(foo(Table, Nodes),
((fun () ->
case mnesia:create_table(Table,[...]) of
{atomic, ok} -> ok;
__Any -> error_logger:error_report(...)
end
end)())).
This is relatively foolproof, but note that the macros don't nest.
/Richard
More information about the erlang-questions
mailing list