Variable Scoping and Nested WITH ... END WITH Commands

Description

When you nest WITH ... END WITH commands, it is important to understand how Xbasic treats variables DIMmed in different name-spaces. If a WITH ... END WITH command is nested within another WITH ... END WITH construct, the inner name-space is called the child name-space and the outer name-space is the parent name-space. Any variable that is DIMmed in the parent name-space will be visible in the child name-space. Any variable that is DIMmed in the child name-space will not be visible in the parent name-space (unless the variable name is prefixed with the name-space name, as in: name-space.variable ). The following Xbasic script demonstrates this. In this script, "A" is the parent name-space and "B" is the child name-space. The variable, firstname is DIMmed in the parent name-space. It is therefore visible in the child name-space.

with a
   firstname = "Peter"
    ui_msg_box("In name-space A","Firstname: " + firstname)
    with b
        lastname = "Pan"
        ui_msg_box("In name-space B","Lastname: " + lastname)
        ui_msg_box("In name-space B","Firstname: " + firstname)

The second message box displayed the value "Peter" because even though the "B" name-space is active, firstname was DIMmed in the parent name-space, and Xbasic "sees" firstname in the parent name-space. Since firstname was DIMmed in the "A" name-space, this command sets firstname in the "A" name-space.

firstname = "Paul"
        ui_msg_box("In name-space B","Firstname: " + firstname)
    end with

The next message shows "Paul" (the value set when name-space 'B' was active).

ui_msg_box("In name-space A","Firstname: " + firstname)

The only way to refer to lastname is to use the "b." prefix, since this variable was created in the "B" name-space.

ui_msg_box("In name-space A","Lastname: " + b.lastname)

If you do not use the "b." prefix, the variable can't be found. This command generates an error.

ui_msg_box("In name-space A","Lastname: " + lastname)

end with

Selecting the Local Variable Frame 

Xbasic supports a syntax that can be used when setting a variable value. By prefixing the variable name with a period, you tell Xbasic to set the variable in the local variable frame, rather than some higher level variable frame. These examples will help illustrate the point. Astute observers will note that the Xbasic code that is generated for the Web Components now uses this syntax. (See also WITH ... END WITH ) For example:

DIM tmpl.field_infotmpl.fields as P
with tmpl.field_info[1]
.fieldname = "City"
.Scope = "Local"
end with

See Also