Revision as of 22:20, 21 November 2006

Problem

You want to evaluate Erlang code stored in a string.

Solution

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:

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:

-module(test).
-export([test/0]).
test()->
%% Create a code string with unbound variables 'A' and 'B'
String="Results=A+B/2.",
%% Scan the code into tokens
{ok,ErlTokens,_}=erl_scan:string(String),
io:format("ErlTokens are ~p~n",[ErlTokens]),
%% Now parse the tokens into the abstract form
{ok,ErlAbsForm}=erl_parse:parse_exprs(ErlTokens),
io:format("ErlAbsForm are ~p~n",[ErlAbsForm]),
%% Now we need to bind values to variable 'A' and 'B'
Bindings=erl_eval:add_binding('A',20,erl_eval:new_bindings()),
NewBindings=erl_eval:add_binding('B',45,Bindings),
io:format("The bindings are ~p~n",[erl_eval:bindings(NewBindings)]),
%% Now evaluate the string
io:format("Going into erl_eval:exprs~n",[]),
{value,Value,_}=erl_eval:exprs(ErlAbsForm,NewBindings),
io:format("Value is ~p~n",[Value]).