Page 1 of 1

Stage 99: For-loop and the shortcut operator

Posted: Wed Mar 09, 2022 7:05 pm
by frank
The recent support for shortcut operators (stages 96-97) has a positive effect on the SharpBASIC language overall. Not only did it improve the loop-statement (see stage 98), it also allowed for a for-statement with an acceptable syntax, something we've been struggling with for months.

A C-like for-statement, which has been adopted by many languages never was an option for SharpBASIC, nor were constructs with a step or by clause to influence the loop direction and steps. But the shortcut operators allow for clean, concise and flexible syntax and they can be applied consistently throughout the language. Let's have a look at an example:

Code: Select all

const a = 0;
const b = 20;

dim i:itr;

main do
  ' even numbers 0-20
  for i = a to b :++ do
    if i % 2 == 0 do
      print(i);
    end
  end
  ' flag loop completed
  print(i == b + 1);
end
The increment operator is obvious and clear and we have several options; :-- for downward iteration, or :+n and :-n for step iterations. The previous example could also have been like:

Code: Select all

' even numbers 0-20
  for i = a to b :+2 do
    print(i);
  end
  ' flag loop completed
  print(i == b + 2);
With this for-statement a new "datatype" called itr (iterator) is introduced. The single reason for this is optimization and flexibility. SharpBASIC currently uses a one-pass top-down parser and it needs to know in advance if a for-statement is present in the next code block. With this fore-knowledge jumps are possible from one or more loops without corrupting the stack. It also improves loop performance.

Iters cannot be initialized upon declaration, nor can they be used as parameter or function type. Similarly, for-statements will not accept other datatypes as iterators. However, SharpBASIC provides both itr (signed) and uitr (unsigned). The next example uses unsigned iter and leaves the value null after the loop:

Code: Select all

' unsigned itr
dim i: uitr;

main do
  ' numbers 10 to 1
  for i = 10 to 1 :-- do
    print(i);
  end
  print(i); ' null
end