Save and Load Variables


sCode$ = SaveCode$(variable {, sCode$ })

sCode$ = LoadCode$(variable, sCode$ )

variable

The variable to be loaded or saved. This must be a variable and not an expression.

sCode$

The encoded data string. This variable is passed in and out of the functions and data is automatically added and removed.

These functions take any variable, array, data structure or Game Engine sprite and returns an encoded string record which can be written to a file or SQLite database. This is very useful in saving and restoring the current program state. These functions were originally added to save the current state of a Game Engine simulation, but they can be used in any program.


data() = [1,2,3,4,5,6,7,8,9,0]

print SaveCode$(data())

1004 1 10 10 1 2 3 4 5 6 7 8 9 0


A delimited item string is returned. The spaces between the numbers are really the tab character "\t". The string produced can be written as a single record to a file. The string contains all the information needed to reinitialize an array later with the loadCode$() function.

Delimited Strings


Multiple variables may be packed into a single text record.


version = 1
timeMs = time()
data() = [1,2,3,4,5,6,7,8,9,0]

code$ = saveCode$(version)
code$ = saveCode$(timeMs, code$)
code$ = saveCode$(data(), code$)

open 1, "LoadSaveTest.dat", "w"
writeln 1, code$
close 1

print code$

1003 1 1003 1467653917996 1004 1 10 10 1 2 3 4 5 6 7 8 9 0


What you get is a serialized text record with all the variable values encoded and ready to be written to a file. Each value is preceded by a type code. The first type (1003) indicates a numeric value.

The variables may then be reloaded using the loadCode$() function. The variables are extracted in the same order that they were encoded.


open 1, "LoadSaveTest.dat", "r"
readln 1, code$
close 1

code$ = loadCode$(version, code$)
code$ = loadCode$(timeMs, code$)
code$ = loadCode$(data(), code$)

print version
print timeMs

for i = 0 to 9
print data(i),
next

1
1467653917996
1 2 3 4 5 6 7 8 9 0


Optionally you may add a version code to the beginning of each record if you think you may be changing your saved data format later. You may need to save more variables later or just change the order of your variables.

Say you wanted to add a comment string variable to your saved data, but still wanted to read old records without the comment. In your save routine add one to the version number and save your comment string with the rest of your data. Then in your load routine use the version number to conditionally read the new variable field.


open 1, "LoadSaveTest.dat", "r"
readln 1, code$
close 1

code$ = loadCode$(version, code$)

code$ = loadCode$(timeMs, code$)
code$ = loadCode$(data(), code$)

comment$ = "No Comment"
if version > 1 then
  code$ = loadCode$(comment$, code$)
endif

print comment$
print version
print timeMs

for i = 0 to 9
print data(i),
next

Save Game Data
2
1467653917996
1 2 3 4 5 6 7 8 9 0







Become a Patron