Erlang Central

String Eval

Revision as of 22:17, 21 November 2006 by (Talk)


You want to evaluate Erlang code stored in a string.


Use erl_scan:string/1 to convert the string into a list of tokens, then use erl_parse:parse_exprs/1 to generate the Erlang intermediate representation, then finally use erl_eval:exprs/2 to generate the final output:

eval(S,Environ) ->
    {ok,Scanned,_} = erl_scan:string(S),
    {ok,Parsed} = erl_parse:parse_exprs(Scanned),

1> eval("A = 1 + 2.",[]).

Now, this is an admittedly baroque way to determine the value of 1 + 2, but it does give you interesting access to the inner workings of the Erlang interpreter.

In addition, you can bind in variables into the string as shown in the test module below:



    io:format("ErlTokens are ~p~n",[ErlTokens]),
    io:format("ErlAbsForm are ~p~n",[ErlAbsForm]),
    io:format("The bindings are ~p~n",[erl_eval:bindings(NewBindings)]),
    io:format("Going into erl_eval:exprs~n",[]),
    io:format("Value is ~p~n",[Value]).

You can compile and run this in the shell:

(arrian@psyduck)17> c(test).
(arrian@psyduck)18> test:test().
ErlTokens are [{var,1,'Results'},
ErlAbsForm are [{match,1,
The bindings are [{'A',20},{'B',45}]
Going into erl_eval:exprs
Value is 42.5000

online casino tips play free online casino slots slots online bonus gambling online bingo on line casinos online casino tips casino games online online casino net bet online casino