我所工作的应用程序允许将脚本片段嵌入文档中。例如:
SomeText
<* PrintLn("This line is generated by a script"); *>
Some other text
<* PrintLn("This line is generated by a script, too"); *>
Some more lines
结果
SomeText
This line is generated by a script
Some other text
This line is generated by a script, too
Some more lines
我正在使用DWScript。首先,第一个脚本片段被编译并执行。然后是RecompiledInContext的下一个片段,以此类推。在片段中声明的函数/变量等将在所有后续片段中可用。 但是,变量值在片段之间丢失。例如:
SomeText
<* var x: Integer = 5; *>
Some other text
<* PrintLn(x); *>
Some more lines
生成文档后:
SomeText
Some other text
0 <-- I would like this to be 5
Some more lines
这是一个展示问题的样例应用程序:
program POC.Variable;
{$APPTYPE CONSOLE}
{$R *.res}
uses
dwsExprs,
dwsComp,
dwsCompiler;
var
FDelphiWebScript: TDelphiWebScript;
FProgram: IdwsProgram;
FExecutionResult: IdwsProgramExecution;
begin
FDelphiWebScript := TDelphiWebScript.Create(nil);
try
FProgram := FDelphiWebScript.Compile('var x: Integer = 2;');
FProgram.Execute;
FDelphiWebScript.RecompileInContext(FProgram, 'PrintLn(x);');
FExecutionResult := FProgram.Execute;
// The next line fails, Result[1] is '0'
Assert(FExecutionResult.Result.ToString[1] = '2');
finally
FDelphiWebScript.Free;
end
end.
有没有一种方法可以在多次执行之间“传递”或“保留”变量值?
以下是安德鲁答案的更新代码,但该代码不起作用:
begin
FDelphiWebScript := TDelphiWebScript.Create(nil);
try
FProgram := FDelphiWebScript.Compile('PrintLn("Hello");');
FExecution:= FProgram.BeginNewExecution();
FDelphiWebScript.RecompileInContext(FProgram, 'var x: Integer;');
FExecution.RunProgram(0);
WriteLn('Compile Result:');
WriteLn(FExecution.Result.ToString);
FDelphiWebScript.RecompileInContext(FProgram, 'x := 2; PrintLn(x);');
FExecution.RunProgram(0); // <-- Access violation
WriteLn('Compile Result:');
WriteLn(FExecution.Result.ToString);
FExecution.EndProgram();
ReadLn;
finally
FDelphiWebScript.Free;
end
end;