gpt4 book ai didi

delphi - 有没有办法在执行 DWScript 两次时保留变量值?

转载 作者:行者123 更新时间:2023-12-03 14:44:04 25 4
gpt4 key购买 nike

我正在开发的应用程序允许将脚本 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;

最佳答案

您可以尝试使用 BeginNewExecution/RunProgram/EndProgram block 代替(在 DWScript 2.2 上测试):

begin
FDelphiWebScript := TDelphiWebScript.Create(nil);
try
FProgram := FDelphiWebScript.Compile('var x: Integer;');

FExecution:= FProgram.BeginNewExecution();

FDelphiWebScript.RecompileInContext(FProgram, 'x := 2; PrintLn(x);');
FExecution.RunProgram(0);
WriteLn('Compile Result:');
WriteLn(FExecution.Result.ToString);

FDelphiWebScript.RecompileInContext(FProgram, 'x := x + 3; PrintLn(x);');
FExecution.RunProgram(0);
WriteLn('Recompile Result: ');
WriteLn(FExecution.Result.ToString);

FExecution.EndProgram();

ReadLn;
finally
FDelphiWebScript.Free;
end
end.

关于delphi - 有没有办法在执行 DWScript 两次时保留变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10958101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com