Humanities Home page   Office of Digital Humanities
Back     BYU LiveCode Lessons Gateway

Digital Humanities & Technology 210

The LiveCode Scripting Language: Continued

Objectives

By the end of this reading you should be able to answer the following questions, within the context of LiveCode:

  1. What is a Boolean value?
  2. What is a Boolean expression?
  3. What is a "control structure"?
  4. Describe the "if" control structure and its forms.
  5. Describe the "switch" control structure and its forms.
  6. Describe the "repeat" control structure and its forms.

blue asterisk Where did this term come from?

George Boole, mathematician

George Boole, 1815–1864, was an English mathematician who invented a system of logical algebra, known today as Boolean logic. He is considered the father of the field of computer science.


Learn more:

http://www.scoopweb.com/George_Boole
http://www.kerryr.net/pioneers/boole.htm
http://en.wikipedia.org/wiki/George_Boole

Boolean Values and Conditional Structures

A Boolean value is simply a value of either true or false. Sometimes Boolean values are referred to as binary values, because they can only have one of two values—e.g., on or off, 0 or 1, true or false. In LiveCode Boolean values are expressed by the constants true and false. You create a Boolean variable simply by putting a Boolean value into it:

put true into answerIsCorrect

Relational Operators

In LiveCode, as in any programming language, it is frequently necessary to compare values; that is to discover whether two values or expressions are equivalent, whether one is greater than the other, and so on. For that we have a set of tools called relational operators. Comparing two values using relational operators results in a Boolean expression, because the relationship can only be evaluated to true or false. LiveCode recognizes the standard algebraic comparison symbols as relational operators:

= 'is equal to'
<> 'is not equal to'
< 'is less than'
> 'is greater than'
<= 'is less than or equal to'
>= 'is greater than or equal to'

LiveCode also recognizes these keywords as relational operators:

is same as '='
is not same as '<>'

Boolean Expressions

The word Boolean is also used to describe any expression that results in either a true or false condition. You will use Boolean expressions constantly in LiveCode programming. They are the basis for making decisions in an if-then structure, for instance.

Here are some examples of Boolean expressions:

  the date = "10/13/12"
  myName is "John" --(i.e., is the contents of the variable exactly the same as the contents of the literal?)
  field "score" > 80
  myScore <> yourScore

Comparing Strings:The comparison of words or strings of letters is based on alphabetical order. Consequently, a word that comes before in alphabetical order is considered less than a word that comes after:

Complex Boolean Expressions: The logical operators and, or, and not can be used to build complex logical expressions. Use parentheses to nest or group expressions as necessary. For example:

x = 20 and y < 45 or z >= 90

In this example, because the statement is processed from left to right, the entire statement would resolve to true if the first two expressions were both true or if the third expression were true. If the third expression were false and one of the first two were false, then the whole statement above would resolve to false. Now consider this statement:

x = 20 and (y < 45 or z >= 90)

Since the parentheses force the second group of Boolean expressions to be evaluated first, the entire statement would only be true if the first expression were true and at least one of the other expressions were true.

If Statement

An if-statement is a conditional control structure that allows for checking a certain condition before taking an action. Boolean operators are an essential ingredient in these types of statements. LiveCode has several forms of the if-statement.

Basic Form

The most basic form of the if statement has a beginning, a middle, and an ending, much like a handler:

if condition then
  statement 
end if

where

condition is an expression that resolves to true or false.
statement is any valid LiveCode command or statement.

In a handler an if-then statement would look something like this:

on mouseUp   
  put field "answer 1" into x   
  if x = 3 then 
    put "Your answer is correct!" into field "response"
  end if
end mouseUp

This handler takes the content of a field and puts it into a variable. It then checks to see if the variable's content is equal to 3. If this is true, then an appropriate response is put into another field. If the variable does not contain 3, then the statement is false and the LiveCode statement within the if...end if structure is not executed.

If/Then/Else Form

Often you will want to perform one action if a condition is true and another action is it is false. For this you use the if-then-else form, which simply adds another clause, or section, to the structure:

if condition then
   statement 
 else
   statement 
 end if

where

condition is an expression that resolves to true or false.
statement is any valid LiveCode command or statement.

Here is an example of an if-then-else structure in a handler:

on mouseUp   
  put field "answer 1" into x   
  if x = 3 then 
    put "Your answer is correct!" into field "response"   
  else 
    put "Your answer is incorrect!  Try again." into field "response"
  end if
end mouseUp

Expanding the example used above, the else portion of this statement provides for everything else the variable may contain besides 3. Consequently, for everything but 3 it will indicate that the response is incorrect.

Even though it may seem like extra typing, beginning programmers should get into the habit of using this "complete" form, because it keeps the statement very clean and unambiguous. As you will see later, there are other forms that LiveCode allows. For now, however, just stick to the basic format shown here.

Multiple Statements in if-then Structures

The first two examples of the if-statement only showed one statement in each clause. However, you may include as many statements as you need in both the if and the else clauses:

if condition then   
  statement   
  statement   
  ...
else   
  statement   
  statement   
  ...
end if

where

condition is an expression that resolves to true or false.
statement is any single LiveCode statement.

In a handler, this form of the if/then/else-statement would look something like this:

on mouseUp   
  put field "answer 1" into x   
  if x = 3 then     
    show image "smileyFace"      
    put "Your answer is correct!" into field "response"      
    wait 2 seconds      
    hide image "smileyFace"      
    put empty into field "response"   
  else      
    beep      
    put "Your answer is incorrect!  Try again." into field "response"      
    wait 2 seconds      
    put empty into field "response"   
  end if
end mouseUp

Building upon the example used previously, this handler now does more depending upon the contents of the variable x. If x contains 3 then an image is shown and text is put into a field. The computer waits a few seconds, then hides the image and erases the text. If x contains anything other than 3, then the computer plays the alert sound and gives an appropriate textual response, erasing the text after a few seconds.

The results of a conditional statement or logical expression can be placed into a variable. This consequently makes the variable contain either true or false (hence, becoming a Boolean), enabling the variable to be checked much like a conditional statement. This is desirable in many cases where you would want to confirm a certain condition as being met without evaluating a conditional statement each time. All that needs to be done would then be to check if the variable itself contained either true or false.

To see this in action, imagine that you have some type of exam that contains a listening component. The instructor wishes the students to begin with the listening section before being able to view the pertinent questions. Once they leave the card that gives them access to the sounds, they should not be able to return to listen to it again. This could be accomplished in this manner:

on mouseUp   
  global heardSound   
  if heardSound then      
    beep      
    put "You've already listened to the sounds." into field "response"      
    wait 2 seconds      
    put empty into field "response"      
    go card "Questions 1-12"   
  else      
    go card "Listening Comprehension"   
  end if
end mouseUp

Previously when the stack was opened, the global variable had been given a value with a statement like this: put false into heardSound (this variable would then change depending upon the actions of the user). This handler then accesses the global variable and checks its value. Note how this is done (as opposed to if heardSound = true). Appropriate action then takes place depending upon the value within the variable. As stated before, it is often more appropriate (and legible) to use a Boolean variable in this manner rather than employing a conditional statement.

Again, the if-statement is a powerful tool for getting the stack to execute functions on a conditional basis, i.e., when certain conditions are met.

Other Acceptable Forms

LiveCode tries to provide more flexibility to the programmer as compared to some other languages. Accordingly, there are "simpler", single line forms for the if/then statement. However, these forms can often become confusing, especially when embedding if-then structures within other if-then structures. For the beginning programmer we recommend sticking to the "complete" format shown above, at least until you become very familiar with how if-then structures work. Because you may encounter these single-line forms, they are included for your information.

Single statement form

This form of the if-statement may only be used to execute a single command when a condition is true. Its syntax is:

if condition then statement

where

condition is an expression that resolves to true or false.
statement is any single LiveCode statement.

Practically speaking, the single-line if-then statement would look something like this within a handler:

on mouseUp   
  put field "answer 1" into x   
  if x = 3 then put "Your answer is correct!" into field "response"
end mouseUp
If/Then/Else Single-statement Form
This expanded form of the single-line if-statement provides an alternate else-clause for a statement to be executed when the condition is false. The syntax is similar:

if condition then statement
else statement

where

condition is an expression that resolves to true or false.
statement is any single LiveCode statement.

In a handler, the single-line if/then/else-statement would look something like this:

on mouseUp   
  put field "answer 1" into x   
  if x = 3 then put "Your answer is correct!" into field "response"   
  else put "Your answer is incorrect!  Try again." into field "response"
end mouseUp

Handling Multiple Conditions

Extended if-then-else structures

The if–then–else structure is very good for setting up either-or, true-false decisions in your code. The if ... then line of the structure determines what happens if the condition is true, and the else section determines what happens if the condition is not true.

But what if there are more than two possible values to check? What if, instead of evaluating a true-false condition you want to evaluate, for example, a range of numeric values. Imagine you are creating a quiz with 10 questions. Students who get more than 8 correct are considered in the top tier, students who get 6 to 8 correct are in the middle tier, and those with 5 or lower are in the bottom tier. How can handle this with an if–then–else structure?

LiveCode, like many programming languages, allows you to extend an if-then structure by adding additional else clauses. The code for the example above might look something like this:

  global numberCorrect
  on checkAnswer
    if numberCorrect >= 8 then
      put "Fabulous!" into fld "feedback"
    else if numberCorrect > 5 then
      put "Not bad." into fld "feedback"
    else
      put "Time to hit the books!" into fld "feedback"
    end if
  end checkAnswer

The Switch Statement

In theory the multiple else if clauses can be extended indefinitely to handle many different conditions. However, there is another conditional structure that is better suited for decision structures with many potential outcomes. It is called a switch structure.

The basic format for a switch structure looks like this:

  switch expression or variable
    case value1
      -- do something
      break
    case value2
      -- do something else
      break
    case value3
      -- do something different
      break
    default
      -- what to do if no match found
  end switch

The expression or variable determines the source of the values that are matched in the case clauses. The break statement means “once a value is matched stop here and exit the switch structure.” The optional default section is what executed if no case clauses are matched.

Switch Statement Example

Let’s say we’re building a calendar stack that gives you helpful messages depending on which day of the week it is. You can easily discover which day is it like this:

  put item 1 of the long date into dayOfWeek

Now we can build a switch statement based on the day of the week, like this:

  switch dayOfWeek
    case "Monday"
      beep
      put "Oh, no! Back to work!" into fld "mood"
      break
    case "Friday"
      put "Finally! Time to play!" into fld "mood"
      break
    case "Saturday"
      put "Chores today!" into fld "mood"
      break
    case "Sunday"
      put "My day of rest." into fld "mood"
      break
    default
      put "Humdrum work day." into fld "mood"
  end switch

The switch structure provides a neater look for multiple-value conditional structure than if–then–else structures. It also provides efficiencies under the hood that make it better suited for multiple-value conditional structures.

See the entry for switch in the LiveCode Dictionary for more on how to use this powerful and useful control structure.




Repeat (Looping) Statements

The repeat statement in LiveCode lets you set up looping structures, which allow a series of commands to be repeated under various conditions. Used properly, a repeat loop allows for more efficient coding, since you can reuse multiple lines of code over and over.

The general form of the Repeat statement consists of the key word repeat at the beginning and a matching end repeat at the end, with any number of LiveCode statements between.

repeat loop form
  statement
  ...
end repeat

where

loop form is an expression that determines the type of loop structure, including the conditions for terminating the loop.
statement is any single LiveCode statement.

There are four basic variations of the loop form:

Repeat For

This specifies a fixed number of times the enclosed statements are to be repeated. A simple example would be:

on mouseUp   
  repeat for 4 times      
    show image "Wow!"      
    wait 10      
    hide image "Wow!"      
    wait 10   
  end repeat
end mouseUp

Within this handler, this repeat structure would show and hide the image specified (with pauses between each) four times, creating a blinking image. The repeat structure will execute its statements exactly the number of times specified.

Repeat With

This repeats with a counter variable that can be accessed within the loop. The repeat with statement specifies a variable to use, a start value and an end value. When processing enters the loop the variable is assigned the start value, then is incremented by 1 each time the loop repeats. When it reaches the end value, looping ends. For example:

on mouseUp   
  repeat with count = 1 to 10      
    put count into field "timer"      
    wait 1 second   
  end repeat   
  beep
end mouseUp

This handler utilizes the nature of the repeat loop form to change the content of a field. The repeat control structure creates a variable called "count" and initializes it to 1. The first time through the loop it puts the contents of the variable (the value 1) into a field and waits one second. The repeat structure then increments the contents of count by 1. This value (now 2) is then displayed in the field, and so on up until count contains 10, which is the last value displayed in the field. The repeat loop then finishes and the computer plays an alert sound. This particular handler creates a type of ten-second timer that displays the amount of time passed and alerts when ten seconds have passed.

Repeat While and Repeat Until

These are logically reciprocal forms. The English meaning best conveys it: The repeat while statement repeats the commands inside the loop while a condition is (or remains) true, and repeat until statement repeats commands until a condition becomes true. For example:

on mouseUp   
  put 1 into count   
  repeat while count <= 10      
    put count into field "timer"      
    wait 1 second      
    add 1 to count   
  end repeat   
  beep
end mouseUp

This handler accomplishes the same end as the example given above. However, in this case it is necessary to manually initialize the variable count outside the loop and manually increment it inside the loop for it to function as we would like.
Note: If "<" were used instead of "<=" within the loop form, then the loop would execute only 9 times instead of 10.

Here is an example of the repeat until-statement:

on mouseUp   
  put 1 into count   
  repeat until count > 10      
    put count into field "timer"      
    wait 1 second      
    add 1 to count   
  end repeat   
  beep
end mouseUp

Again, this accomplishes the same end as the previous examples. It is still necessary to manually initialize and increment the variable.
Note: If ">=" were used instead of ">" within the loop form, then the loop would execute only 9 times instead of 10.

Repeat For Each

This is similar to the repeat with structure, except that instead of incrementing a variable, this repeat structure allows one to step through the various elements—characters, words, lines, etc.—within a container. (We will discuss these elements, also called chunks, in more detail in a later lesson.) This structure is useful if you need to manipulate or perform an action on each element within a container, as it is much faster and easier to work with than the repeat with structure. For example:

on mouseUp   
  repeat for each word thisOne in field "fullText"      
    put thisOne & return after field "wordList"   
  end repeat
end mouseUp

This handler steps through the text of the field, one word at a time, and then places each word on a separate line in another field. This type of repeat loop is very useful in cases where you need to examine chunks of text one at a time.


Back     BYU LiveCode Lessons Gateway
Maintained by Devin Asay.
Copyright © 2005 Brigham Young University