The application I am working on allows embedding script sinppets into a document. For example:
SomeText
<* PrintLn("This line is generated by a script"); *>
Some other text
<* PrintLn("This line is generated by a script, too"); *>
Some more lines
Results
SomeText
This line is generated by a script
Some other text
This line is generated by a script, too
Some more lines
I am using DWScript. Internally the first script snippet is compiled & executed. Than the next is RecompiledInContext and executed and so on. A function/variable/etc declared in a snippet becames available in all later snippets. However the variable values are lost between snippets. For example:
SomeText
<* var x: Integer = 5; *>
Some other text
<* PrintLn(x); *>
Some more lines
After generating the document:
SomeText
Some other text
0 <-- I would like this to be 5
Some more lines
Here is a sample application which illustrates the problem:
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.
Is there a way to "transfer" or "keep" the variable values between executions?
Here is an updated code of Andrew's answer which does not work:
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;