使用PaxCompiler做脚本的时候,有的时候我们需要在脚本中引用其他的脚本文件,如果脚本文件放入程序的根目录引用是没有任何问题的,但是我们做脚本的时候不可能脚本都放到程序的根目录,这样引用的会找不到要引用的脚本文件pas,但是PaxCompiler提供了一个事件,可以在脚本编译的时候手工加载引用的pas具体如下:
PaxCompiler1.OnUsedUnit := DoUsedUnit;
function TForm1.DoUsedUnit(Sender: TPaxCompiler; const UnitName: string;
var SourceCode: string): Boolean;
var
List:TStrings ;
begin
if CompareText(UnitName,'PXL') = 0 then
begin
List:=TStringList.Create ;
try
List.LoadFromFile(GetMediaPath+UnitName+'.pas');
SourceCode :=List.Text;
Result:=True ;
Exit ;
finally
List.Free ;
end;
end;
Result:=False ;
end;
var
PaxCompiler1: TPaxCompiler;
PaxInterpreter1: TPaxInterpreter;
PaxPascalLanguage1: TPaxPascalLanguage;
begin
PaxCompiler1 := TPaxCompiler.Create(nil);
PaxInterpreter1 := TPaxInterpreter.Create(nil);
PaxPascalLanguage1 := TPaxPascalLanguage.Create(nil);
try
PaxCompiler1.Reset ;
//PaxCompiler1.OnSavePCU:=DoSavePCU ;
//PaxCompiler1.OnSavePCUFinished:=DoSavePCUFinished;
// PaxCompiler1.AddModule('1', 'Pascal');
// PaxCompiler1.AddCodeFromFile('1',GetMediaPath+'PXL.pas') ;
// if PaxCompiler1.Compile(PaxInterpreter1, true, false) then
// begin
// PaxInterpreter1.SaveToFile(GetMediaPath+'PXL.PCU');
// end;
//
PaxCompiler1.OnUsedUnit := DoUsedUnit;
// PaxCompiler1.OnSavePCU:=DoSavePCU ;
// PaxCompiler1.OnSavePCUFinished:=DoSavePCUFinished;
// PaxCompiler1.OnLoadPCU:=DoLoadPCU;
// PaxCompiler1.OnLoadPCUFinished:=DoLoadPCUFinished;
PaxCompiler1.RegisterLanguage(PaxPascalLanguage1);
PaxCompiler1.AddModule('1', 'Pascal');
PaxCompiler1.AddCodeFromFile('1', GetMediaPath+'script.pas');
{参数二 是否保存引用文件的PCU,参数三 是否将PCU文件作为运行时包}
if PaxCompiler1.Compile(PaxInterpreter1, False, false) then
begin
//PaxInterpreter1.Run ;
PaxInterpreter1.SaveToFile(GetMediaPath+'script.bin');
end
else
begin
ShowMessage(PaxCompiler1.ErrorMessage[0]) ;
end;
finally
FreeAndNil(PaxCompiler1);
FreeAndNil(PaxInterpreter1);
FreeAndNil(PaxPascalLanguage1);
end;
end;
为了保证运行的效率,在程序开始的时候或者直接发行编译成二进制的脚本文件会更有效率,否则的话在手机平台下,就编译一个空的脚本文件也是需要很长时间的,程序会发生明显的卡顿,更不要说每次执行脚本都先编译再执行,那如果再手机平台下,程序估计会卡的死死的,通过上面的编译就可以生成一个二进制的包,每次执行脚本我们都执行那个二进制的脚本文件就可以了,省略了每次编译的过程,程序速度是非常快的,省略编译的步奏,脚本的执行速度和delphi自己的执行速度是差不多的, PaxCompiler自带的例子里面有测试,具体执行二进制脚本代码如下:
var
PaxInterpreter1: TPaxInterpreter;
begin
PaxInterpreter1 := TPaxInterpreter.Create(nil);
try
PaxInterpreter1.LoadFromFile(GetMediaPath+'script.bin');
PaxInterpreter1.MapGlobal;
PaxInterpreter1.Run;
finally
FreeAndNil(PaxInterpreter1);
end;
end;