Requires: Variants.lg32
To save and load numerical, string and array Variant types from and to a file or a datablock.
value = VarLoad([channel%], [datablock])
datablock = VarSave(data, [channel%][, options])
channel% | : File I/O channel |
data | : Variant data to be saved |
datablock | : String |
options | : Integer |
value | : Variant |
The main purpose of VarSave is to write a Variant Array to either an open file or a formatted datablock which can then be encrypted and saved later. By default, the function will store numerical, string and embedded arrays; when it encounters Variants of a different type (Objects, Pointers, etc.) which can not be saved and then restored later, it saves these as Empty values.
There are three options available with which the operation and/or ouput of VarSave can be altered:
VARSAVE_SHOWERRORS | If this is set, rather than converting incompatible Variant types to Empty, an error is thrown. |
VARSAVE_ADDCRLF | This option adds the CRLF (Carriage Retiurn - Line Feed) characters at the end of the formatted data. |
VARSAVE_PACKED | As an output datablock from a reasonably sized array can be very long, this option automatically packs the output of the function to make it more compact. |
VarLoad is then used to retrieve the pre-formatted data either from the file I/O channel or a pre-loaded datablock.
Both functions can also be used to store and retrieve individual Variants as well as Variant Arrays.
$Library "Variants.lg32"
// Create TextBox object
// Note: you can not use an Object variable in Array so you must assign it to a Variant
Dim obj As Variant : Ocx TextBox txt : Set obj = txt
// Create the Variant Array
// Note: If you add txt instead of obj, GB32 adds txt as a Handle, not an object
Dim a = Array(1, 2.2, Array("Dog", "Cat", 144.56), obj)
// Open data file
Dim f$ = App.Path & "\test.dat" : Open f$ for Output As # 1
// Save the Array as a datablock first, then packed to the data file
// Note: Even when saved to file, VarSave will still return a datablock
Dim a$ = VarSave(a), b$ = VarSave(a, 1, VARSAVE_PACKED)
// Close the data file
Close # 1
// Show the comparative lengths of the packed and unpacked datablocks
Debug "Unpacked length:";Len(a$)
Debug "Packed length:";Len(b$)
// Open the data file again, this time for Input...
Open f$ for Input As # 1
// ...load the Array into two new variants, first from the datablock, then from file...
Dim b = VarLoad( , a$), c = VarLoad(1)
// ...show that all three Arrays are the same (except where object is now empty)...
Debug VarPrint(a, VARPRINT_ARRAYINFULL)
Debug VarPrint(b, VARPRINT_ARRAYINFULL)
Debug VarPrint(c, VARPRINT_ARRAYINFULL)
// ...and close and delete the data file
Close # 1
Kill f$
Debug.Show
// This line will cause an error when it reaches the object obj in the array
a$ = VarSave(a, , VARSAVE_SHOWERRORS)
{Created by James Gaite; Last updated: 05/10/2022 by James Gaite; Other Contributors: Jean-Marie Melanson}