Closures in DWScript / OP4JS

Closures, also known as “anonymous methods” in Delphi, are now supported by DWScript for the JavaScript CodeGen, with the same syntax as in Delphi:

myObject.MyEvent := procedure (Sender : TObject);
                    begin
                       ...
                    end;

There are of course some extensions that go beyond what Delphi supports 😉

You are allowed to use a named local procedure as a closure / anonymous method, with optional capture of local variables, allowing for neater layout of code, for instance:

begin
   ...
   procedure MyLocalProc(Sender : TObject);
   begin
      ...
   end;
   ...
   myObject.MyEvent := MyLocalProc;
   ...
end;

The function pointers and closures are unified, you did not have to distinguish between a “procedure” and a “procedure of object“, and you don’t have to distinguish a “reference to procedure” either, ie. if you declare

type TNotifyEvent = procedure (Sender : TObject);

as long as the parameters match (and result type for a function) , the above type will accept standalone functions, object methods, interface methods, and now closures/anonymous methods (and even record methods, which are just syntax sugar for standalone function with an implicit parameter).

PS: DWScript (as a scripting engine), will very likely evolve (in time) from a stack based-engine to a closure-based engine, so the above syntax will be supported for scripting purposes too, and not just when compiling to JavaScript.

3 thoughts on “Closures in DWScript / OP4JS

  1. Very nice.
    Even if I do not like very much anonymous methods, and do not mind writing some short methods or even classes for such purpose. If you take a look at the Delphi implementation of closures (when local variables are involved), there is a lot of “hidden” code generated. And I always like to know how the generated asm (or execution stack for a script) will look like, when I code. 🙂
    Could you provide some general links about closure-based engine for runtime execution? I understand that e.g. DWS and LUA have a stack based runtime, but I don’t get the “closure” thing in term of execution runtime – or is it just a feature, not a proper design?

Comments are closed.