Stage 98: Loop statement does it

Follow the development of the SharpBASIC compiler and share your thoughts and ideas.
Locked
User avatar
frank
Site Admin
Posts: 40
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands
Contact:

Stage 98: Loop statement does it

Post by frank »

The new shortcut operators (see stages 96-97) allow for a more flexible and readable loop statement, so flexible in fact that SharpBASIC's count statement (aka the for-loop) has almost become superfluous and certainly "ugly" (keep in mind this is still pre-alpha stage).

Consider the following example:

Code: Select all

dim i:int;

main do
  ' print numbers 1 to 10
  loop i = 0 do
    while i < 10; i:++;
    print(i);
  end
end
The flexibility lies in the fact that the while (or until) condition can be put at the top or the bottom of the loop. In Addition, the increment or shortcut operator can be placed anywhere inside the loop, i.e. it is not bound to the condition statement. The shortcut operators also allow for steps without the need of a step or by keyword:

Code: Select all

dim i:int;

main do
  ' print numbers 1 to 10, step 2
  loop i = 0 do
    while i < 10; i:+2;
    print(i);
  end
end
Finally, multiple shortcut operators may influence the iterator in a single loop:

Code: Select all

dim i:int;

main do
  ' titius-bode law
  loop i = -3 do
    print((i+4)*15);
    if i < 3 do
      i:+3;
    else do
      i:*2;
    end
    while i <= 384;
  end
end
The possibilities are almost endless. Even jump statements and labels are allowed inside the loop statement. Needless to say this should be done with care.

Of course, the basic loop remains:

Code: Select all

dim n:int=1;

main do
  loop do
    while n < 11;
    print(n);
    n = n + 1; ' (or n:++)
  end
end
 
Last edited by frank on Wed Mar 09, 2022 7:30 pm, edited 5 times in total.
Keep it simple!
Locked