Game Development Reference
In-Depth Information
How the Code Works
It is rather easy. Most of the code is similar to what we used in writeToFileSingle , which involves
opening a file, but in read mode instead. (If you do not specify a mode while opening a file to read,
the default mode is read mode). Then we use the read function with the "*a" parameter to read the
entire contents of the file. This is fine for this scenario, as we only have a small amount of data to
read. Then we close the file and return the data read from the file.
Potential Issues
These two functions work well for loading and saving data. But, as mentioned, it's not good to have
local results = {}
local hfile =io.open(filename)
if hfile==nil then return end
for line in hfile:lines() do
table.insert(results, line)
end
return results
end
There are a couple of differences in this code as compared to the earlier code. The first is that we
use an array table called results to store everything we read from the file. The next is that instead
of using hfile:read("*a") to read the content, we use hfile:lines() to get one line at a time from
the file. The newline character (Enter) separates the data and is the delimiter between the two lines.
Once we get this data, we store it into the array results by using the table.insert function to add
the data to the end of the table.
Once we get the array returned to us, the positioning of the data is important. The positions of the
data shall be fixed, so we need to know in advance what position coincides with what data.
Saving Data to a Variable
Here's a quick tip on how to manipulate global variables. In Chapter 2, you read about a variable _G ,
which is actually a table object and holds all the global variables, functions, and so on. When we
declare a variable (without local scope), it is assigned to this table as a global variable. What we are
going to do in this quick exercise is declare a global variable, read the value of the variable, and then
manipulate it using the _G table.
myVar = 1
print(myVar)
myVar = myVar + 1
print(_G["myVar"])
 
Search WWH ::




Custom Search