- DelphiTools - https://www.delphitools.info -

New “for var” syntax in DWScript

Latest DWScript SVN introduces support a new “for var” syntax extension for loops.

It combines the loop with the loop variable declaration (type-inferred), while scoping the variable to the loop.

The syntax of “for to/downto” loops is thus extended to:

On first approximation, it can considered to be a form of syntax-sugar for:

begin
   var someVarName := lowBound;
   for someVarName := someVarName to highBound do begin
      ...loop code here...
   end;
end;

So someVarName is accessible immediately after it has been defined, which means it can be used in the to/downto, where it will be evaluated once before the loop is entered (like any to/downto expression) ie. this is allowed

for var i := functionCall() to i+10 do ;
for var e := myEnum to High(e) do ;

To avoid risks of confusions, an extra rule is added on top of the above sugar:

the loop variable name cannot be the same name as another variable in the same scope

This means you can’t use “for var” to hide a local variables, and the following code will result in a compilation error:

var i : Integer;
for var i:=1 to 10 do ;

Note that someVarName is scoped to the “for var” statement, so you can have multiple “for var” statements in the same procedure using the same var name without running afoul of the previous rule, ie. this will not give an error

for var i:=1 to 10 do ;
for var i:=10 downto 1 do ;
var i : Integer;

As a reminder, note that scoping of “classic” loops in DWScript (with un-scoped variables) remain unchanged, ie. unlike in Delphi (and other languages), the loop variable is always well-defined after the loop as ended or if the loop is exited through “break”. Also loop bounds (and steps) are always evaluated only once, before entering the loop.

The new language feature is available right now for DWScript, and will be in the next SmartMobileStudio [1] version.