nielsAD / lape

Scripting engine with Pascal-like syntax for FPC and Delphi
112 stars 26 forks source link

Q: How can I re-run the script without recompiling? #194

Open zamtmn opened 8 months ago

zamtmn commented 8 months ago

Is it possible? If you just do it like this

program Project1;

uses
  Classes, Sysutils, lpparser, lpcompiler, lpinterpreter;

const
  MyScript =
             'var a:Int32=10;' + LineEnding +
             'begin'           + LineEnding +
             '  WriteLn(a);'   + LineEnding +
             '  a:=20;'        + LineEnding +
             '  WriteLn(a);'   + LineEnding +
             'end.';

var
  Compiler: TLapeCompiler;
begin
  Compiler := TLapeCompiler.Create(TLapeTokenizerString.Create(MyScript));
  try
    if Compiler.Compile() then
      RunCode(Compiler.Emitter);
      RunCode(Compiler.Emitter);
  except
    on E: Exception do
      WriteLn(E.ToString());
  end;
  Compiler.Free();

  ReadLn;
end. 

it save prev variables and print

10
20
20
20

How to make reuse right?

ollydev commented 8 months ago

Hi, I just added a commit that should help.

if Compiler.Compile() then
begin
  States := Compiler.getVarStates();  // once compiled, store global variable values

  RunCode(Compiler.Emitter);

  Compiler.setVarStates(states);  // now restore var states before re-running 
  RunCode(Compiler.Emitter);

  Compiler.freeVarStates(states);   
end;

Beware that variable states are gathered with assign operator so multidimensional arrays would not be restored correctly.

zamtmn commented 8 months ago

Thank you, this will suit me already, but I'll ask if a complete solution for arrays is planned?

ollydev commented 8 months ago

Yes, I will add deep copy for arrays shortly