Delete a built-in identifier in TFPExpessionParser
Original Reporter info from Mantis: wp @wpam
-
Reporter name:
Original Reporter info from Mantis: wp @wpam
- Reporter name:
Description:
While the BuiltinIdentifiers needed by TFPExpressionParser allow to add functions and variables there is no way to delete an existing identifier. A possible use case, for example, is to replace the trigonometric functions by degree-aware functions as requested in a forum post (https://forum.lazarus.freepascal.org/index.php/topic,19627.msg341477.html#msg341477).
A patch is provided.
Steps to reproduce:
The following code works after application of the patch:
program Project1;
uses
Math, fpExprPars;
var
parser: TFPExpressionParser;
idx: Integer;
Procedure ExprCos(Var Result : TFPExpressionResult; Const Args : TExprParameterArray);
begin
Result.resFloat:=Cos(DegToRad(ArgToFloat(Args[0])));
end;
begin
idx := BuiltinIdentifiers.IndexOfIdentifier('cos');
BuiltinIdentifiers.Delete(idx);
BuiltinIdentifiers.AddFunction(bcMath, 'cos', 'F', 'F', @ExprCos);
parser := TFPExpressionParser.Create(nil);
try
parser.BuiltIns := [bcMath];
parser.Expression := 'cos(45.0)';
WriteLn(parser.Evaluate.ResFloat:0:5);
parser.Expression := 'cos(90.0)';
WriteLn(parser.Evaluate.ResFloat:0:5);
parser.Expression := 'cos(180.0)';
WriteLn(parser.Evaluate.ResFloat:0:5);
finally
parser.Free;
end;
WriteLn('Press ENTER to close.');
ReadLn;
end.
Additional information:
Without the patch, an ugly cast to a descendant of TBuiltInManager would be needed to access the protected Defs collection.
type
TMyBuiltinManager = class(TExprBuiltinManager);
var
idx: Integer;
...
idx := BuiltinIdentifiers.IndexOfIdentifier('cos');
TMyBuiltinManager(BuiltinIdentifiers).Defs.Delete(idx);
BuiltinIdentifiers.AddFunction(bcMath, 'cos', 'F', 'F', @ExprCos);
Mantis conversion info:
- Mantis ID: 36396
- Fixed in version: 3.3.1
- Fixed in revision: 43636 (#575fd849)
- Target version: 3.2.0