58 of 172
ZBasic Language Reference 51 ZX Microcontroller Family Dim i as Byte, j as Byte i = 44 Test.i = 55 For j = 0 to 1 Dim i as Byte For i = 1 to 3 Dim i as String i = "Hello" Debug.Print i Debug.Print CStr(Main.i) Debug.Print CStr(Test.i) Next i Next j End Sub The first Debug.Print will display the string "Hello" because it refers to the variable i that is defined in the body of the innermost For loop. The second Debug.Print will display the value 44 because it refers to the variable i defined at the outermost level of the subroutine using the subroutine name qualifier. The third Debug.Print will display the value 55 because it refers to the module-level variable i using the module qualifier. Within the body of the innermost For loop, there is no way to access the loop index variable because it is hidden by the local definition. There is no qualifier that can be added to a variable reference to resolve to outer block scope levels except the block formed by the routine definition itself. Since ZBasic implements true block scoping, one advantage to using variables defined within compound statements is that, in addition to the restricted visibility, the stack space used by the variables can be reused by local variables defined in subsequent compound statements. Example If (j > 5) Then Dim i as Byte i = 12 Call PutPin(i, zxOutputLow) Else Dim s as Single s = 3.14159 debug.print CStr(s) End If For k = 1 to 10 Dim b as Byte b = GetPin(13) Debug.print CStr(b) Next k In this example, the three variables i, s and b share the same stack space. That works because none of them are “active” at the same time. BasicX Compatibility Note In BasicX mode, block scoping of variables is not supported. It is permitted to define variables within a compound statement but the effect is the same as if they were defined at the beginning of the routine.