Control Structures

From Kolmafia
Revision as of 01:26, 14 March 2010 by imported>StDoodle
Jump to navigation Jump to search

Conditional

if

if ( boolean )
{
   // any statements here
	 // are only going to be executed
	 // if the boolean returns true
}


description=Single-statement conditionals may omit the curly braces.

else

if ( boolean )
{
   // statements if true
}
else
{
   // the statements here
	 // are only going to be executed
	 // if the boolean returns false
}

else if

code=

if ( boolean1 )
{
   // statements if true
}
else if ( boolean2 )
{
   // the statements here
	 // are only going to be executed
	 // if boolean1 returns false
	 // & boolean2 returns true
}

{{{code}}}

switch

 switch (value) 
 {
   case expression:
     statement
     statement
     ...
     break;
   default:
     statement
     statement
     ...
     break; 
 }

while

 while (boolean)
 
 {}

repeat until

 repeat
 {}
 until (boolean);

for

 for x from a to b by c

is the general case. You don't need to specify whether it's going up or down - although doing so by using upto or downto does allow a runtime check to make sure you didn't screw up.

If you don't specify "c", it defaults to incrementing/decrementing by 1. The first iteration is at a and the last is at b (that is to say, it goes from a to b, inclusive).

foreach

 foreach x in map
 
 {}

"map" must be an aggregate - a map or a slice. x takes on each value of the map index in turn. If there is more than one index, x iterates over the first index.

For example:

 boolean [int][string] map;
 map[15]["test"] = true;
 foreach int_index in map
 {
   print(int_index); //this will print '15' once, since there is only one valid value for this index
   foreach string_index in map[int_index] //this iterates over the "slice" of the map where 1 is fixed as the index
   { 
     print(string_index); //This will print "test" once, since there is only one valid value for this index
     print(map[int_index][string_index]); //this will print "true"
   }
 }

So the output is

 15
 test
 true

Note that instead of nesting foreach statements, for a multidimensional map, two iterators can be used inline.

 foreach x,y in map

is identical to

 foreach x in map
 {
   foreach y in map[x]
 }

See http://kolmafia.sourceforge.net/advanced.html#maps for more details on maps.

continue/break

Like many languages with looping structures, ASH supports the break and continue statements. All looping structures (for, while, repeat until, and foreach) support these statements.

 break;

Breaks out of the smallest enclosing loop. In a switch statement, breaks out of the switch statement. Execution resumes at the first statement after the end of the loop/switch statement.

 continue;

Continues on to the next iteration of the loop (skipping any statments in this iteration that occur after the continue statement). In a switch statement, continue is allowed iff the switch is inside a loop, and acts as any other continue.