我正在开发的应用程序允许将脚本 sinppets 嵌入到文档中。例如:
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;