Talk:For
Jump to navigation
Jump to search
Overstuffing the for
The complete syntax of the loop for is:
for( initializer, initializer, ...; condition; increment, increment, ... ) loop
We can use as many initializers and increments as we want, separated by commas.
For example, to initialize the start and end values, which even looks interesting to use:
list num; integer totNum; integer i;
// totNum = llGetListLength(num);
//
// for ( i = 0, totNum = llGetListLength(num); i < totNum; i++)
// {
//
// }
for ( i = 0, totNum = llGetListLength(num); i < totNum; i++)
{
}
Other examples look more weird than useful, but they work:
- Adding the elements of a list of numbers:
list num = [ 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ];
integer sum; integer totNum; integer i;
for ( i = 0, totNum = llGetListLength(num), sum = 0; i < totNum; sum += llList2Integer(num, i), i++); // no loop body
llOwnerSay("sum = " + (string)sum);
- Counting dice rolls until getting a double six:
integer dice1; integer dice2; integer roll;
for ( roll = 0, dice1 = 0, dice2 = 0; dice1 < 6 || dice2 < 6; roll++, dice1 = (integer)llFrand(6) + 1, dice2 = (integer)llFrand(6) + 1 ); // no loop body
llOwnerSay("Double six after " + (string)roll + " rolls");
- Packing two fors in one:
integer i; integer j;
// for ( i = 0; i < 5; i++ )
// {
// for ( j= 0; j < 3; j++ )
// {
// llOwnerSay("i=" + (string)i + " j=" + (string)j);
// }
// }
for ( i = 0, j = 0; i < 5; j++, i += (j == 3), j *= (j != 3) )
{
llOwnerSay("i=" + (string)i + " j=" + (string)j);
}
- Three in one:
integer i; integer j; integer k;
// for ( i = 0; i < 5; i++ )
// {
// for ( j= 0; j < 3; j++ )
// {
// for ( k = 0; k < 4; k++ )
// {
// llOwnerSay("i=" + (string)i + " j=" + (string)j + " k=" + (string)k);
// }
// }
// }
for ( i = 0, j = 0, k =0; i < 5; k++, j += (k == 4), k *= (k != 4), i += (j == 3), j *= (j != 3) )
{
llOwnerSay("i=" + (string)i + " j=" + (string)j + " k=" + (string)k);
}
SuzannaLinn Resident (talk) 07:09, 24 October 2024 (PDT)