Game Development Reference
In-Depth Information
This is more or less what our code looked like earlier, only we have added a variable called lineNo
and we keep incrementing it based on the lines read. When lineNo is 1, we save the value we have
read into the variable score . Then we save lineNo 2 into lives , and so on, till lineNo is 4, after which
(if there are more lines) we just don't read them.
Potential Issues
In your app, the number of variables that you might store could be different for each application.
You would never know the order in which your data is saved, and if the order of saving the data
or reading the data is changed, you might have values that end up in the wrong variables. Most
importantly, it would be near impossible to set up multiple if .. then statements to load the
local hfile = io.open(filename)
if hfile == nil then return
local results = {}
local a = 1
for line in hfile:lines() do
_G[resTable[a]] = line
a = a + 1
end
end
We read through the data one line at a time, and with each loop, we increment the index variable a .
We store the value that we have read into a global variable with a name specified in the array.
For example, if we had specified in our array that we wanted the values to be Line1 = Score ,
Line2 = Lives , and Line3 = health , then the function will automatically create global variables with
these names and assign the value to them.
This function will now read the data, save it into the array table, and access it via the global variable.
However, we need to pass it the table that is modified for this.
local aryTable = {
"Score",
"Lives",
"Health,
}
We call the function simply as follows:
readFromFile("datafile", aryTable)
This method has its own set of problems. What if we were to add some data in aryTable not at the
end, but in the middle? This would make the variables all mixed up and in the wrong places. So how
do we fix that? There are many easy ways to approach this issue, and each has its own set of pros
 
Search WWH ::




Custom Search