The "intelligent" behavior of a computer program depends upon its ability to make choices at runtime. These choices generally take the form of evaluating some expression and executing or not executing a particular block of code depending on how the evaluation turns out at that moment.
One major form of choice is branching . We have a line or block of code that can be executed optionally. The computer evaluates a boolean expression, called a condition . If the condition is true, the line or block of code is executed; if it isn't, the line or block of code is skipped, and execution jumps to the line that follows it.
In AppleScript, branching control is performed with if. An if block comes in several forms. The basic form is a single block of code that is executed only if a condition is true. If the condition is false, the block is skipped, and execution resumes after the end if line.
if condition then -- what to do if condition is true end if
It is also permitted to supply a second block with else, to be executed if the condition is false. One or the other of the two blocks will be executed.
if condition then -- what to do if condition is true else -- what to do if condition is false end if
Another syntax lets you specify multiple conditions. AppleScript will execute the first block whose condition is true, skipping the others. It is permitted to supply, with else, a final block that will be executed if none of the conditions is true.
if condition1 then -- what to do if condition1 is true else if condition2 then -- what to do if condition2 is true -- ... same for condition3, condition4, etc. [else] -- what to do if none of them is true end if
So, for example:
set x to random number from 1 to 10 set guess to text returned of
There's also a single-line form :
if condition then whatToDo
In the single-line form, whatToDo is any valid expression or single-line command (it can even be another single-line if).