Skip to content
Paul Lipkowski edited this page Apr 17, 2021 · 16 revisions

Loop is a syntax structure of PapajScript, that allows executing an instruction (or a set of them) multiple times. The first loops were introduced on January 12, 2018, along with the update for RPN Calculator 0.3.0.

First loops

The first ever introduced loop is times-loop, which has 2 syntaxes

Name Syntax Purpose Since Last supported version
times-loop Xn I1 Do I1 n times (n >= 1) 0.3.0 0.4.1
times-loop N1 times I1 Do I1 N1 times 0.3.1 supported today

Currently supported loops

Syntaxes

Name Syntax Purpose Since
times-loop N1 times I1 Do I1 N1 times 0.3.1
while-loop while ( B1 ) I1 While B1 is true, do I1 0.5.0
do-while-loop do I1 while ( B1 ) Repeat doing I1 while B1 is true 0.5.0
do-until-loop do I1 until ( B1 ) Repeat doing I1 until B1 is true 0.5.0
for-loop for ( I1 ; B1 ; I2 ) I3 Start a loop with I1 and while B1 is true, do I3 and then I2 0.5.0
for-each-loop for ( E1 : A1 ) I1 For each element E1 from array A1 do I1 0.5.1

Notes

  • A for-each-loop may overwrite array items' values when assigning
  • As of 0.5.1.1 version, for-each-loop must contain a pre-defined array, so for ( $i : $T sortNumbers ) { } does not work. A kind of workaround is $T sortNumbers -> $U for ( $i : $U ) { }
  • A for-each-loop is able to change array's values by default. Since April 17, 2021 (earliest stable version 0.5.2) it is possible to restrict the loop from editing the array by using const word, e.g. for ( const $i : $T )

Examples

  • 10 times { 100 random } which generates 10 numbers from a range [0..99] (note: we must know the exact amount of iterations here)
  • 1 >i while ( i 10 <= ) { 100 random i ++ >i } which also generates 10 numbers from a range [0..99]
  • 1 >i do { 100 random i ++ >i } while ( i 10 <= ) which also generates 10 numbers from a range [0..99]
  • 1 >i do { 100 random i ++ >i } until ( i 10 > ) which also generates 10 numbers from a range [0..99]
  • for ( 1 >i ; i 10 <= ; i ++ >i ) { 100 random } which also generates 10 numbers from a range [0..99]
  • for ( item : [ 1 1 10 seq ] ) { i println } prints a sequence from 1 to 10
for ( 1 -> i ; i 5 <= ; i ++ -> i ) { 
    i i * println
} // print squares of numbers 1..5
for ( i : [ 1 1 5 seq ] ) { 
    i i * println
} // print squares of numbers 1..5
[ 1 1 5 seq ] -> $T
$T println // prints [ 1 2 3 4 5 ]
for ( $i : $T ) { 
    $i $i * println
} // print squares of numbers 1..5, i.e. 1, 4, 9, 16, 25
$T println // prints [ 1 4 9 16 25 ]
[ 1 1 5 seq ] -> $T
$T println // prints [ 1 2 3 4 5 ]
for ( const $i : $T ) { 
    $i $i * println
} // print squares of numbers 1..5, i.e. 1, 4, 9, 16, 25
$T println // prints [ 1 2 3 4 5 ]
Clone this wiki locally