Branching

Branches make your program jump. You can use them to make your program go to a section that is used many times, or enter or leave a loop.

A. LBL and GOTO

Remember the TOOLBAR statement? Those funny little things we wrote after each ITEM. Those are a form of GOTO. We usually spell it out: GOTO label makes the program execution jump to the line which says LBL label. IMPORTANT: Be very careful not to have more than one identical LBL statement, especially in long programs when it can be difficult to remember.Let's try an example with the GETKEY() function:

DemoLG()
prgm
lbl A
getKey()->K
If K=13
Goto B
Goto A
Lbl B
Endprgm


Let's examine what this does. First, it stores the last button pressed in K. If K=13 (the last key was enter), the program jumps to LBL B at the end of the program. If K wasn't 13, we skip that line and end up at GOTO A. This makes us jump back to the beginning (where LBL A is). In other words, we wait until enter is pressed, then end the program. This is not the best way to write this routine, but it is a simple example of LBL and GOTO.

B. Calling other programs

Up until now, everything we've done has been within one program. Calling another program is fairly simple. Just type the name of the program and the double parenthesis. What if we want to pass a value to another program? Well, that's a fairly simple process. Just put the value in the parenthesis. Ex:

DemoA()
prgm
local A
Dialog
Title "Program Calling"
Request "String",A
Enddlog
DemoB(A)
Dialog
Title "Done"
Text "Cool, huh?"
Enddlog
Endprgm

DemoB(x)
prgm
local x
Dialog
Title "Hey"
Text "You entered "&x
Enddlog
Endprgm


Notice that the variables are local. So A only exists in DemoA and X only exists in DemoB. DemoB cannot call the value of A, but by sending the value of A to DemoB, it stores it in the local variable X. Note: The variables here don't need to be local, I made them local to show a case where a local variable can be used in another program (actually the variable isn't, its value is copied to a local variable of the second program).

If you understood conditional statements and branching, you should be fine. The next two sections are pretty easy. Now, just to be sure you're paying attention, another quiz:

Quiz 3: Conditional Statements and Branching

1. What would happen if I typed Hello("Grant") in the home screen?

Hello(V)
Prgm
local v
Dialog
Title "Yo"
Text "Hi "&V
Enddlog
Endprgm


Answer: A dialog box would read "Hi Grant"

2. What does this program do?

DemoF()
Prgm
1->x
lbl A
If x=42
Goto B
x+1->x
Goto A
Lbl B
Dialog
Title "Ford Prefect says..."
Text "That's the meaning of life!"
Enddlog
Endprgm


Answer: It will loop 42 times then tell you something that any geek should know.

There are still two important functions we haven't learned yet: LOOP and FOR. But you will soon realize that they are just simple forms of things you have already done.

<<Previous - Contents - Next>>