Sharing+PRIVATE+variables

//by Richard Russell, May 2007//

The [|PRIVATE] statement allows you to create variables (also arrays, structures etc.) which are //private// to a procedure or function, in the sense that they retain their values from one call to the next, but are not visible to the rest of the program.

Occasionally you might want two or more procedures or functions to //share// PRIVATE variables, so that they are accessible by those procedures/functions but not by the rest of the program. BBC BASIC has no built-in facility for doing this, but it is possible to achieve an equivalent effect using one or other of the methods described here.

Method one
This method relies on providing a common //entry point// for the procedures and functions, so that the **PRIVATE** statement may be placed there, as follows:

code format="bb4w" DEF PROCone(parameters) : LOCAL type% : type% = 1 DEF PROCtwo(parameters) : LOCAL type% : type% = 2 PRIVATE alpha, beta%, gamma$ CASE type% OF       WHEN 1: REM. Code for PROCone goes here. WHEN 2: REM. Code for PROCtwo goes here. ENDCASE ENDPROC code This method can be expanded to as many procedures and functions as are required to share the PRIVATE data. It is even possible to share the data between a procedure and a function, so long as the **ENDPROC** or **=** statement is placed within the appropriate **WHEN** clause:

code format="bb4w" DEF PROCone(parameters) : LOCAL type% : type% = 1 DEF FNtwo(parameters) : LOCAL type% : type% = 2 PRIVATE alpha, beta%, gamma$ CASE type% OF       WHEN 1: REM. Code for PROCone goes here. ENDPROC WHEN 2: REM. Code for FNtwo goes here. = returnvalue ENDCASE REM. Execution should never reach here. code

Method two
This method relies on creating a **structure** to hold the private data, as follows:

code format="bb4w" DEF PROCone(parameters) PRIVATE ps{} PROCprivate(ps{}) REM. Code for PROCone goes here. REM. Private variables are ps.alpha, ps.beta%, ps.gamma$ ENDPROC DEF FNtwo(parameters) PRIVATE ps{} PROCprivate(ps{}) REM. Code for FNtwo goes here. REM. Private variables are ps.alpha, ps.beta%, ps.gamma$ = returnvalue DEF PROCprivate(RETURN t{}) PRIVATE p{} DIM p{alpha, beta%, gamma$} !(^t{}+0) = !(^p{}+0) !(^t{}+4) = !(^p{}+4) ENDPROC code The **PROCprivate** procedure sets the supplied structure parameter to point to the private structure declared therein, allowing any routine which calls this procedure to access the private data.

You can use the same technique to share PRIVATE arrays:

code format="bb4w" DEF PROCone(parameters) PRIVATE array PROCshare(array) REM. Code for PROCone goes here. ENDPROC DEF FNtwo(parameters) PRIVATE array PROCshare(array) REM. Code for FNtwo goes here. = returnvalue DEF PROCshare(RETURN a) PRIVATE array DIM array(100) !^a = !^array ENDPROC code