KBL Conditional Logic

IFs, GOTOs and LOOPS: An Introduction to Conditional logic in KBL

 

 

KBL has been designed to maximise a linear-style of logic scripting - considerably more so than in most conventional IT languages; however, conditional or "branching" logic still has a very important role in KBL script writing in a wide range of business process flow scenarios. Here are some typical examples of requirements and 'business rules' where conditional logic is probably needed:

  • You only have access to a function IF you are an administrator
  • You can only buy a particular product IF you are domiciled in the UK or the EU
  • We can only accept orders on the Mk 1 Widget IF there are more than 5 in stock.
  • IF Mk 1 Widget stock level falls below 10, 20 more are automatically ordered
  • IF a client does not have two items of evidence that they reside in the UK, perform the alternative ID check
  • Display and edit the selected customer records - from the first to the last or, UNTIL the user exits the function.
  • IF the customer's age is < 16 or is > 89, ask the user to verify date of birth.
  • When taking and order, IF the customer's outstanding unpaid balance plus the order value is greater than the pre-set credit limit, send a request to your supervisor to raise the credit limit.
  • Check the recorded word list, IF more than three words on the keyword watch list occur, mark the recorded text string with a referral alert.
  • Only accept orders from 0800 to 1930 unless an override ordering period has been set. 

The reason for the term 'conditional logic' is that an instruction for an action to take place (or not), depends on doing something if a certain condition is met or persists. Upon applying the condition check, the outcome could be to continue with the current process or path or alternatively, branch to a different one. In KBL the commands that control this are:

IF, IF ELSE and IF END

GOTO and LABEL

LOOP, LOOP CONTINUE, LOOP BREAK and LOOP END

 

They can be used separately or in combination to create the logic you need. If required, they can be "nested", I.E IFs can be used within IFs, IFs within LOOPs, LOOPs within LOOPs, etc., etc. BUT there is one stipulation that must be met - an IF must be matched with an IF END, a LOOP with a LOOP END and a GOTO with a LABEL. If you omit the end of a conditional clause your script may start to give you unpredictable results. Bear this in mind when writing with these types of commands

 

The IF Command

 

The simplest form is:

IF IS  -some condition is true-

  Then we execute commands in here

IF END

....after which we carry on processing

 Examples

Assuming the following parameter values:

  • PAR XVAL = 10.5, 
  • PAR ZVAL = 1
  • PAR WSTRING = "John Smith"
  • PAR YSTRING = "Harry Lime"

In KSE KBL we can test the following conditional logic

Using numeric values

IF IS [XVAL] = 10.5    Test for a precise value (here it's TRUE)

IF IS [XVAL] != 10.5 Test for XVAL not equal to 10.5 (TRUE)

IF IS [XVAL] = [ZVAL] Test for a precise value (FALSE)

IF IS [XVAL] > [ZVAL] Is XVAL greater than ZVAL? (TRUE)

IF IS [XVAL] >= [ZVAL] Is XVAL greater or equal to ZVAL (TRUE)

IF IS [XVAL] < [ZVAL] Is XVAL less than  ZVAL (FALSE)

Using text strings

NOTE for text strings with spaces put double quotes around them including parameters.

IF IS "[WSTRING]" = "JOHN SMITH"    Are the strings the same? Here TRUE because = is NOT case sensitive. 

IF IS "[WSTRING]" == "JOHN SMITH"  Are the strings the same? Here FALSE because == IS case insensitive

IF IS "[WSTRING]" == "John Smith"    Strings the same? Here TRUE because == IS case insensitive for strings

IF "[WSTRING]" == "[YSTRING]" Strings the same? Here FALSE because == IS case insensitive for strings but the strings are not the same

KBL IF command examples

IF IS [INPUT_CLICKED] = CANCEL
  MSG "No Action Taken script ends" // Message if the cancel button on a form is clicked
  EXIT    // followed by the script exiting
IF END

In this next example, we introduce the IF ELSE condition

// Age validation
IF IS [CUST_AGE} > 89
  MSG "Customer age is input as [AGE] years, please confirm age is correct"
  Standard.INPUT.YESNO "Please Confirm Customer age is [AGE]" // request verification
IF ELSE [CUST_AGE] < 18
  MSG "Customer's age is too young for Product X, Please correct or decline the order"
IF ELSE
  MSG "Order Accepted"
  GOTO Process_Order
IF END

Note in the above, the IF ELSE introduces an alternative within the IF clause. IF ELSE can be used as a catchall OR it can have a further test here we wanted to test for values outside a permitted age range. Note, sometimes, IF, IF ELSE, IF END logic is referred to Boolean logic - where the outcome of the condition check is either TRUE or FALSE. Where branching logic starts to get complicated, it can help to resolve matters by thinking in Boolean terms.

Conditional logic and dates

Working with date parameters can sometimes be frustrating, this is primarily due to the fact that different systems use different formats. For hassle free data comparisons, the trick in KBL is to represent your dates in a common, numeric format. The ideal is yyyyMMdd (so comparing dates is made simple)

IF IS [DATE_OF_BIRTH] < 19000101    // for illustration usually parameterised
  MSG "Date of birth given is before 01/01/1900, please check"
IF END

If your original date format is not in this format (e.g. read from a spreadsheet or .csv), you can use the following KBL utility command to convert:

PAR DOB = 23/11/1899 // Example in the starting format
UTIL.DATE /PAR DATE_OF_BIRTH [DOB]    //[DOB] is the parameter in dd/MM/yyyy format
UTIL.DATE.REFORMAT FROM dd/MM/yyyy TO yyyyMMdd // now changed to yyyyMMdd

The value returned in DATE_OF_BIRTH will be 18991123  - much easier to work with logically.

 

The GOTO Command

 

The GOTO command, as the name implies, instructs the KBL processor to jump to another defined point in the script. The position to jump to is specified by a LABEL .

GOTOs are invariably used with other conditional script clauses e.g an IF clause. So in the previous, IF example, if the customer age was in the right range, after the message, the KBL processor would jump to the Process_Order label in the script.

Examples

LABEL Answer_Question

// Create a form to ask a question
INPUT.CLEAR
INPUT.DEF /TITLE "What is 5 + 23 ?"
INPUT.DEF /FIELD  Answer TEXTBOX "Your Answer" 100 default 0
INPUT.SHOW /CLEAR
INPUT.GET /PARS // Turn Answer into a parameter
 
IF IS [INPUT_CLICKED] = CANCEL
  GOTO FINISH // If user clicks cancel got to Finish
IF END
 
IF [ANSWER] != 28
  MSG "Wrong answer - try again"
  GOTO Answer_Question    // go back to displaying the form
IF ELSE
  MSG "Right Answer"

IF END

LABEL FINISH

MSG "Goodbye"
EXIT

In the example above, there are two GOTO commands within IF clauses so depending on whether the user provides an incorrect answer or cancels the operation, the focus of the script will be moved to the Answer_Question or Finish label. Note, if the user continues to provide an incorrect answer, the script will never complete. The script will end if the CANCEL key is clicked or the right answer is entered. Ensure that your IF and GOTO logic always has a means of exit!

Make sure that every GOTO command has a matching LABEL otherwise your logic could malfunction unpredictably.

 

The LOOP Command

 

More will be said of the LOOP and related commands in KSP (KBL Studio Plus) as it's a key logic component for application building but it does have many uses in KSE. LOOP enables you to cycle around a defined piece of command script while a condition persists. It is most commonly used where an incrementing index parameter, or counter is required. For example, you need to display / edit / perform selective logic on stored records such as a Customer records dataset. Source data is IMPORTed from a file into MAIN (or another in-memory dataset), work is done using an INPUT form. You want to be able to visit each record (or a subset of records) and perhaps edit them. The record you currently display, is the current MAIN row number AND the index number of the LOOP cycle.

The LOOP command has a number of options (use the command Help screen and Intellisense to view all the options) but if you are doing work on a dataset then the following is a typical construction.

// Loop all rows in MAIN, where the index parameter L1 is the current rowno 

MSG "Starting work on Customer records"
LOOP L1 TAB MAIN    // Loop Starts Here
MSG "Working on record number [L1]"
..Do something like display or edit a record in MAIN for row [L1]

// but you might want to skip to the next record
IF IS - a condition is True - 
  MSG "Skip record number [L1]"
  LOOP CONTINUE    // discontinues work on the current record and skip to the next one
IF END

...continue processing loop logic

 // You might want to exit the function entirely
IF IS - a condition is True - 
  MSG "Stop record processing after record [L1]"
  LOOP BREAK    // break out of the loop, continue from the next command after LOOP END
IF END
 ..continue processing loop logic
LOOP END    // Loop Ends Here

...continue processing your script after the LOOP has finished

MSG "Finished work on Customer records"

Another simple Loop example: Here we'll keep displaying a message after waiting a predefined number of seconds. We control the potential number of cycles of the loop but we'll put a test in it to spare us the boredom after 5 loops

LIMIT LOOP 100    // Limit loop to 100 times (while testing)
WAITSECONDS = 2
NCYCLES = 1000

LOOP [NTIMES] NO_TIMES [NCYCLES] /  / NTIMES is the Index, NCYCLES is the no. of times to loop
IF IS [NTIMES] > 5
   MSG "Stopping on cycle [NTIMES]" // will be 6!
   LOOP BREAK // break out of the loop if the condition is met
IF END
WAIT [WAITSECONDS] //  wait a few seconds before displaying a message
MSG "[NTIMES] you waited [WAITSECONDS] to see this message"
LOOP END

 

Summary

So the combination of IFs, GOTOs and LOOPs gives you great control of your logic flow. Note that each type of conditional logic can be placed inside the other types and that you can "nest" logic (e.g. IFs within IFs) but be careful not to overcomplicate things as it's easy to get into a muddle!

Before you use conditional logic, think about whether you really need it and, if you do, keep it as simple as you can. Beware using too many GOTOs, avoid them if you can (often it's possible to use IF, IF ELSE for a cleaner design). Always make sure you have an "escape route" so that you don't go around in an infinite loop and have to break out of your script session.

Try and design in a modular fashion, use SECTIONS to compartmentalise your code. Please note that some of the more advanced ways of using conditional logic and scripting reusable, callable *FUNCTIONs will be available in KSP so if your KSE scripts seem to be over complex, consider upgrading to KSP when it becomes available.

*KBL FUNCs are scripts written as callable routines that perform a set calculation or function, they have defined inputs and outputs and can share the same in memory datasets (MAIN, STORE, etc.) as the calling script. FUNCs are not available in KSE. Think of a FUNC as you own defined command.

 Â

Back to top