这可以使用此链接中提到的 erl_scan、erl_parse、erl_eval 来实现。问题在于变量绑定。在表达式中使用时需要知道变量绑定(在 fun 中更难)
1> Expr="Awesome = 41 + 41.".
"Awesome = 41 + 41."
2> {ok, Tokens, _} = erl_scan:string(Expr).
{ok,[{var,1,'Awesome'},
{'=',1},
{integer,1,41},
{'+',1},
{integer,1,41},
{dot,1}],
1}
3> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
{ok,[{match,1,
{var,1,'Awesome'},
{op,1,'+',{integer,1,41},{integer,1,41}}}]}
4> {value, Value, Binding} = erl_eval:expr(Form, []).
{value,82,[{'Awesome',82}]}
当用户Awesome = 41 + 41.
在浏览器中输入时,您可以将响应发送回 82。
您还需要维护表达式的状态。也就是应该保持的Binding可以使用如下
5> FunStr ="io:format(\"Awesome = ~p\", [Awesome]).".
"io:format(\"Awesome = ~p\", [Awesome])."
6> {ok, Tokens1, _} = erl_scan:string(FunStr).
{ok,[{atom,1,io},
{':',1},
{atom,1,format},
{'(',1},
{string,1,"Awesome = ~p"},
{',',1},
{'[',1},
{var,1,'Awesome'},
{']',1},
{')',1},
{dot,1}],
1}
7> {ok, [Form1]} = erl_parse:parse_exprs(Tokens1).
{ok,[{call,1,
{remote,1,{atom,1,io},{atom,1,format}},
[{string,1,"Awesome = ~p"},
{cons,1,{var,1,'Awesome'},{nil,1}}]}]}
8> {value, Fun1, _} = erl_eval:expr(Form, Binding).
{value,82,[{'Awesome',82}]}
9> {value, V, _} = erl_eval:expr(Form1, Binding).
Awesome = 82{value,ok,[{'Awesome',82}]}
绑定列表应该增长到会话结束。