Reputation: 1328
Is it possible somehow to retrieve variable value by its name (name represented as string)?
% we are calling foo function as foo(3)
foo(Param) ->
Var1 = Param * 2,
% some magic code here which can evaluate
% "Var1" string to Var1's value (6)
ok.
I want to implement (if it is possible) some kind of logger macro, like
Param = 3*4,
% This should write "My parameter value is 12" to log
?LOG("My parameter value is $Param").
Thanks.
Upvotes: 1
Views: 452
Reputation: 1328
Thanks to Dmitry Belyaev for mentioning parse transform. Say we have logging code:
?dump("My parameter value is $Param")
What I need here is to parse variables within format string ("My parameter value is $Param") with some regular expression. This format string contains single var name (Param). And we need to insert io_lib:format function call (by transforming original AST) with modified format string:
print_message(io_lib:format("My parameter value is ~p~n", [Param]))
In result we can archive required behavior:
Bar = "hello",
Buzz = buzz123,
?dump("Say $Bar to $Buzz"),
% => example:19: Say "hello" to buzz123
You can look at my implementation here
Upvotes: 1
Reputation: 2593
The common way to log is to have formatting string and list of parameters. However your idea is achievable through usage of parse transform.
Upvotes: 1
Reputation: 2005
For toy problems you could use:
io:format("My parameter value is ~p~n", [Param]).
Alternatively:
error_logger:info_report/1
or other error_logger
functions.
The logging library lager
is commonly used.
Upvotes: 0