Game Development Reference
In-Depth Information
If we open a file, we are responsible for closing it too. When we try to open a file using the io.open
function, it returns the file handle and a string that contains the reason for the failure (if it fails to open
the file).
To save our value using this function, we simply call
writeToFileSingle(score, "score")
writeToFileSingle(health, "health")
and so on.
Congratulations, you have now written code to save a variable, and it can be run in the interactive
Lua shell, as expected.
Note Irrespective of which platform you choose as a developer, the preceding Lua code should work
across most of the platforms and Lua frameworks.
Grabbing the Data
In addition to saving data, we also need to retrieve it. In a game, dumping data that we cannot retrieve
is as good as not saving any data at all. We have, with the earlier function writeToFileSingle , saved
our data to a variable. Now comes the tricky part: reading the values from the file.
In theory, reading the data from a file should be the reverse process of writing to the file. So, we
open the file that we have saved our data into and then we read all of the data from the file.
function readFromFileSingle(filename)
local hfile = io.open(filename, "r")
if hfile==nil then return end
local value = hfile:read("*a")
hfile:close()
return value
end
Since we've saved our data using the writeToFileSingle function, we can retrieve our data easily,
like so:
print(readFromFileSingle("score"))
print(readFromFileSingle("health"))
Note Since the data is one piece of information per file, the order in which you save it and the order
in which you load it shouldn't matter.
If the file does not have any data, it just returns nil , which pretty much means the same and can be
managed if required.
 
Search WWH ::




Custom Search