// Calling javascript methods on variants creates temporary variant arrays for passing parameters.
// To avoid access violations after freeing the runtime, make sure all your code using Variants gets out of scope first.

procedure Test(Context: TChakraCoreContext);
var
  Global, Json, MyObj: Variant;
begin
  // assign javascript Global to a Variant
  Global := JsValueToVariant(Context.Global);

  // read its (JSON) property and assign it to another Variant
  Json := Global.JSON;

  // call its method, assign result to another Variant
  MyObj := Json.parse('{ "name": "world" }');

  // access property
  Writeln(Format('Hello, %s!', [MyObj.name]));

  // call another method
  Writeln(Json.stringify(MyObj));
end;

procedure Main;
var
  Runtime: TChakraCoreRuntime;
  Context: TChakraCoreContext;
begin
  Runtime := nil;
  Context := nil;
  try
    Runtime := TChakraCoreRuntime.Create;
    Context := TChakraCoreContext.Create(Runtime);
    Context.Activate;

    Test(Context);
  finally
    Context.Free;
    Runtime.Free;
  end;
end;