【问题标题】:How I can evaluate an expression which contains the `Pi` constant using ICompiledBinding?如何使用 ICompiledBinding 评估包含“Pi”常量的表达式?
【发布时间】:2012-07-05 08:50:48
【问题描述】:

我正在使用ICompiledBinding 接口来评估简单的表达式,如果我使用像(2*5)+10 这样的文字可以正常工作,但是当我尝试编译类似2*Pi 的东西时,代码会失败并出现错误:

EEvaluatorError: 找不到 Pi

这是我当前的代码

{$APPTYPE CONSOLE}

uses
  System.Rtti,
  System.Bindings.EvalProtocol,
  System.Bindings.EvalSys,
  System.Bindings.Evaluator,
  System.SysUtils;


procedure Test;
Var
  RootScope : IScope;
  CompiledExpr : ICompiledBinding;
  R : TValue;
begin
  RootScope:= BasicOperators;
  //Compile('(2*5)+10', RootScope); //works
  CompiledExpr:= Compile('2*Pi', RootScope);//fails
  R:=CompiledExpr.Evaluate(RootScope, nil, nil).GetValue;
  if not R.IsEmpty then
   Writeln(R.ToString);
end;

begin
 try
    Test;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

那么如何使用 ICompiledBinding 接口评估包含 Pi 常量的表达式?

【问题讨论】:

    标签: delphi delphi-xe2


    【解决方案1】:

    据我所知存在两种选择

    1) 您可以使用传递BasicOperatorsBasicConstants 作用域的TNestedScope 类初始化IScope 接口。

    (BasicConstants Scope 定义了 nil、true、False 和 Pi。)

    Var
      RootScope : IScope;
      CompiledExpr : ICompiledBinding;
      R : TValue;
    begin
      RootScope:= TNestedScope.Create(BasicOperators, BasicConstants);
      CompiledExpr:= Compile('2*Pi', RootScope);
      R:=CompiledExpr.Evaluate(RootScope, nil, nil).GetValue;
      if not R.IsEmpty then
      Writeln(R.ToString);
    end; 
    

    2)您可以使用这样的句子手动将 Pi 值添加到 Scope。

    TDictionaryScope(RootScope).Map.Add('Pi', TValueWrapper.Create(pi));
    

    代码将如下所示

    Var
      RootScope : IScope;
      CompiledExpr : ICompiledBinding;
      R : TValue;
    begin
      RootScope:= BasicOperators;
      TDictionaryScope(RootScope).Map.Add('Pi', TValueWrapper.Create(pi));
      CompiledExpr:= Compile('2*Pi', RootScope);
      R:=CompiledExpr.Evaluate(RootScope, nil, nil).GetValue;
      if not R.IsEmpty then
      Writeln(R.ToString);
    end;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多