Xbasic GuideConditional Statements

Conditional statements execute code blocks when a specific condition is met.

IF statements

The most common and useful conditional statement in the Xbasic language uses the IF ... THEN ... ELSE ... END IF syntax. The statement begins by testing whether an expression is true. If the expression is true (.T.), the statement after the THEN clause executes. If the expression is false (.F.), the statement after the ELSE clause is executed.

For example, copy the code below into the Interactive Window and run it:

today = now()
weekday = dow(today)
IF (weekday = 1 .OR. weekday = 7) THEN
    msg = "Business is closed."
    msg = "Business is open."
showvar(msg,"Open or Closed?")

In the example above, the now() function is used to get the current date. It then uses the dow() function to get the weekday. The weekday is then tested to determine what message to display. If it is the weekend (Sunday (1) or Saturday (7)), then the business is closed. Otherwise, the business is open.

ELSE IF can be used to create multiple test cases in an IF statement. If the IF statement contains multiple tests, the code following the first expression that evaluates to .T. executes. If no IF...ELSE IF tests evaluate to .T., the ELSE condition is executed. Run the code below in the Interactive Window:

IF (weekday = 1 .OR. weekday = 7) THEN
    msg = "No work today! It is the weekend."
ELSE IF (weekday = 2) THEN
    msg = "It is the first day of the work week."
ELSE IF (weekday = 6) THEN
    msg = "It is the last day of the work week."
    msg = "It is the middle of the work week."
showvar(msg,"Work week")

If weekday is 1 (Sunday) or 7 (Saturday), the script displays the message that it is the weekend. Otherwise, if weekday is 2 (Monday), then a message is shown stating that it is the first day of the work week. Otherwise, if weekday is 6 (Friday), then the message states it is the last day of the work week. If weekday is any other value, then the ELSE condition is executed, and we see a message that it is the middle of the work week.

SELECT Statements

IF...THEN...ELSE statements become tedious when you have more than two alternatives. The SELECT...CASE language element provides a much easier way to test for multiple conditions. The SELECT...CASE statement allows you to test any number of expressions. The statements immediately following the first expression that evaluates to .T. are executed up to, but not including, the next CASE statement. Run the following code in the Interactive Window:

today = now()
weekday = dow(today)
msg = ""
    CASE weekday = 1
        msg = "Today is Sunday"
    CASE weekday = 2
        msg = "Today is Monday"
    CASE weekday = 3
        msg = "Today is Tuesday"
    CASE weekday = 4
        msg = "Today is Wednesday"
    CASE weekday = 5
        msg = "Today is Thursday"
    CASE weekday = 6
        msg = "Today is Friday"
    CASE weekday = 7
        msg = "Today is Saturday"
showvar(msg,"Day of Week")