How Did the ZX Spectrum Plus Store BASIC Variables?
The Sinclair ZX Spectrum+ utilized a specific memory architecture to manage user-defined variables within its BASIC interpreter, relying on a contiguous block of RAM designated for variable storage. This article explores the underlying memory structure, detailing how variable names, types, and values were organized sequentially in memory. We will examine the variable allocation process, the critical role of the system variable VARS, and the specific byte formats used for storing numeric and string data within the interpreter.
The core of variable storage lay in the system variable known as VARS, located at memory addresses 23627 and 23628. This two-byte pointer held the address of the start of the variable area in RAM. Unlike modern systems that might use hash tables or complex structures, the ZX Spectrum BASIC interpreter stored variables in a simple linear list. As new variables were created during program execution, they were appended to the end of this list, and the VARS pointer was updated to reflect the new end of the variable space. This method allowed for quick sequential access but meant that finding a specific variable required scanning the list from the beginning until a match was found.
Each entry in the variable list began with the variable name stored as ASCII bytes. To distinguish the end of a name, the interpreter set bit 7 of the last character byte to 1. For a simple numeric variable like “A”, the stored byte would be 193 (65 for ‘A’ plus 128). For a string variable like “A$", the dollar sign was part of the name, so the sequence would be 65 ('A') followed by 163 (35 for '$’ plus 128). This naming convention allowed the interpreter to parse the variable list without needing separate delimiters between the name and the value.
Following the name bytes, the actual data was stored according to the variable type. Numeric variables occupied exactly five bytes using the Sinclair floating-point format. This format consisted of one byte for the exponent and four bytes for the mantissa, allowing for a wide range of values despite the limited memory. String variables were handled differently; the interpreter stored a length byte followed by the ASCII characters of the string itself. Because string lengths could vary, this made the memory footprint of string variables dynamic, unlike the fixed size of numeric variables.
Memory management was strictly controlled to prevent variables from overwriting the BASIC program or the system stack. The variable area grew upwards in memory from the address pointed to by VARS. If the variable list grew too large and collided with other memory regions, the system would trigger an “Out of memory” error. This rigid structure defined the limitations of ZX Spectrum+ programming, requiring users to be mindful of variable usage, particularly when handling large arrays or long strings that could quickly consume the available 48K of RAM.