Skip to content

3.3 Variables and scope

6502Nerd edited this page Nov 15, 2020 · 1 revision

How dflat handles variables

By default, all variables used in dflat are global, like most early variants of BASIC - despite the fact that code can only executed through defined procedures. It's an important note which is easily forgotten, even by me!

However, there is the provision to make variables 'local' in the following sense; the current value of a variable can be saved to a procedure's stack frame, which will be restored when the procedure exits. There are ways this happens;

  • Through explicit use of the local keyword to command dflat to save a variable value to the stack
  • Default behaviour for parameter variables (i.e. those named variables in definitions signatures)

Why does dflat do it like this? Primarily it's performance; the language is targeted at 8 bit systems, having to manage stack frames by default takes time and for many simple uses (for which dflat is best suited), is not needed.

Regarding parameter variables, these would also have been global by default, but it's awkward to define a way to make these local to the procedure without looking ahead, hence they are local by default. But if required, these parameter variables can also be made global with an & qualifier although note this is not the same as passing by value and passing by reference as one might see in other languages - it is simply whether the variable is placed on the procedure's stack frame (local) or not (global).

The following example shows the main scenarios;

  • 100 def_test(a,&b)
  • 110 local c
  • 120 a=1:b=2
  • 130 c=9
  • 140 enddef
  • 150 ;
  • 200 def_main(c,d)
  • 210 a=-1
  • 220 _test(c,d)
  • 230 println a," ",b
  • 240 println c," ",d
  • 250 enddef
  • _main(3,4)

When _main(3,4) is invoked from the command line, the output is;

-1 2

3 4

This is what's going on;

  • 200 : value of 3 and 4 loaded in to c and d respectively
  • 210 : a is set to -1
  • 220 : _test is invoked with the value of c and d (3 and 4)
  • 100 : current value of a (-1) is pushed on to the stack and set to 3
  • 100 : because of the & qualifier, current value of b is not pushed on to the stack, but is set to 4
  • 110 : the current value of c (3) is pushed on to the stack
  • 120 : a is set to 1 (was 3), b is set to 2 (was 4)
  • 130 : c is set to 9 (was 3)
  • 140 : the value of a (was 1) is restored from the stack back to -1 and returns to the statement after invocation
  • 230 : prints the value of a and b; notice the values are -1 and 2
  • 240 : prints the value of c and d; notice the values are 3 and 4