如果它足夠簡單(即使有可選參數),基於TStringList的東西實際上工作得體。這裏有一個簡單的例子,讓你開始:
type
TCommandRec = record
Command: string;
Proc: array(AArgs: TStringList);
end;
const
Commands: array(0..4) of TCommandRec = (
(Command: 'New'; Proc: DoNew),
(Command: 'Customer'; Proc: DoCustomer),
(Command: 'Run'; Proc: DoRun),
(Command: 'Scr'; Proc: DoScr),
(Command: 'Find'; Proc: DoFind));
procedure RunScript(const AFileName: string);
var
Script, Args: TStringList;
i, j: Integer;
begin
Script := TStringList.Create;
try
Script.LoadFromFile(AFileName);
Args := TStringList.Create;
try
Args.Delimiter := ' ';
for i := 0 to Script.Count - 1 do begin
Args.DelimitedText := Script[i];
for j := Low(Commands) to High(Commands) do
if SameText(Args[0], Commands[j].Command) then begin
Commands[j].Proc(Args);
Break;
end;
end;
finally
Args.Free;
end;
finally
Script.Free;
end;
end;
procedure DoRun(AArgs: TStringList);
begin
if SameText(AArgs[1], 'End-of-day') then
RunEndOfDayProcess
else if SameText(AArgs[1], 'Hourly') then
RunHourlyProcess
else
raise EInvalidScript.Create;
end;
procedure DoFind(AArgs: TStringList);
var
FindType: string;
begin
if (AArgs.Count <> 5) or not SameText(AArgs[2], 'by') then
raise EInvalidScript.Create;
if SameText(AArgs[1], 'Cust') then begin
if SameText(AArgs[3], 'Name') then
FindCustomer(AArgs[4], '')
else if SameText(AArgs[3], 'LastName') then
FindCustomer('', AArgs[4])
end
else if SameText(AArgs[1], 'Contact') then begin
...
end
else
raise EInvalidScript.Create;
end;
如果你有多個可選參數(例如,FIND CUST BY NAME John AND LASTNAME Smith
)然後,而不是硬編碼的StringList偏移就像我之前所做的那樣,刪除了的StringList你每個參數處理它(或將其添加到您的查詢)。這樣,當它是空的時候,你知道你已經完成了這一行,而你只需要看看AArgs[0]
看看你是否認出了下一個位。
該腳本語言應該有多複雜?如果只是一些相對簡單的命令,你可以使用'TStringList'來解析命令行。 – jpfollenius 2010-03-24 18:03:56
以及它遠離TStringList實現,它有許多可選參數,如: 命令>按名稱查找客戶約翰* 命令>通過電話查找聯繫人0012541 * 因此,您可以看到命令結構是我的考慮點,可能參數的有效性。 我希望它是一個靈活的系統,可以根據我的客戶需求隨時添加\修改命令。 – Objectsberg 2010-03-24 18:29:27