Skip to main content

Traverse Loop

generated description: personi

From the example on the previous page, you can see that traversing a tree involves using Traverse() repeatedly. Let's use a loop to make it easier, and traverse another level of the tree. The code in the example below is so common when working with globals that you should study it closely.

It starts by initializing a variable, ln, to the empty string. Then, the Do/Loop begins. The assignment statement uses Traverse() to produce the subscript value of the first child of the ^PersonI("Name") node, a last name. Next, the If command checks to see if the loop should end, looking for a last name equal to the empty string. Finally, the code does something with the last name, in this case simply writing it. And then the loop repeats itself, retrieving the next last name. Notice how the code doesn't produce the phone numbers, even though they are “next to” the names, because the phone numbers are not siblings of the names.

The assignment statement using Traverse() is similar to typical programming statements like i = i + 1, using the current value of a variable to produce a new value.

ln = ""
    ln = traverse(^PersonI("Name", ln))
    if ln = "" then exit do
    println ln

The example code is in the simpleloop subroutine of BAStraverse.BAS. Run it using the Terminal.

SAMPLES>do simpleloop^BAStraverse()

FeedbackOpens in a new tab