I know I can test the value with IF or CASE, but if I have hundred of values this method will be much faster and more effective then to
check condition hundred of times with IF or CASE.
There must be a reason why someone invented ARRAYS and LISTS (TList, TStringList, TObjectList, TDictionary, fpList, fpHashList... etc.).
Why don't you load your GCodes from a *.txt file to an ARRAY or use a DATABASE if you don't want to store everything inside the RAM.
GCodes inside of a String... ?
BTW:
I like the way from @KemBill, but without the class overkill, just one procedure... very easy....
But "MethodAddress" uses a For-Loop and this should be faster than a TDictionary ????
UNIT Unit1;
{$MODE OBJFPC}{$H+}{$J-}
Interface
USES
Classes, SysUtils, Forms, Controls, Dialogs;
TYPE
TProc = Procedure Of Object;
TYPE
TForm1 = Class(TForm)
Procedure FormCreate (Sender: TObject);
Procedure FormClick (Sender: TObject);
Procedure GCodeExec (ProcName: ShortString);
Procedure G21;
Procedure G28;
Procedure G30;
PRIVATE
strGCode: ShortString;
End;
VAR
Form1: TForm1;
Implementation
{$R *.LFM}
Procedure TForm1.GCodeExec(ProcName: ShortString);
Var
M: TMethod;
Begin
M.Code:= Self.MethodAddress(ProcName);
If Assigned(M.Code)
Then
Begin
M.Data:= Pointer(Self);
TProc(M);
End;
End;
Procedure TForm1.FormCreate(Sender: TObject);
Begin
strGCode:= 'G28';
End;
Procedure TForm1.FormClick(Sender: TObject);
Begin
GCodeExec(strGCode);
End;
Procedure TForm1.G21;
Begin
ShowMessage('G21');
End;
Procedure TForm1.G28;
Begin
ShowMessage('G28');
End;
Procedure TForm1.G30;
Begin
ShowMessage('G30');
End;
END.
@Munair: Please ask YODA if your way is "Keep it simple". I think your way is a pain and a growing pain in the future...
And is that faster than a Dictionary or a HashList ???