Game Development Reference
In-Depth Information
and cons. However, the best method would be to get the name of the variable and the value of the
variable from the file.
Writing Data to the File
We have written some code to read our data from the file. Now we'll write some code to write the
data, which could be read using the preceding function.
function writeToFile(filename, resTable)
local hfile = io.open(filename, "w")
if hfile == nil then return end
local i
for i=1, #resTable do
hfile:write(_G[resTable[i]])
end
end
The code for writing the data to the file is not very different. We open the file in write mode, and then
we iterate through the list of variables that we want to save to the file. These are found from the
resTable parameter passed. So, whatever we have in this table, the function shall attempt to save
those variables to the file.
Saving a Table
We just saved data that is in the form of either strings or numbers. If the data to be saved is anything
else, the functions will start to fail, and more so if the variable is a table. The biggest issue with
tables is iterating through the depths of the table.
If you were to use any other programming language, you would hear, “Why not serialize the data?”
I'll explain why this isn't a good idea in Lua.
The mark of good developers is their ability to avoid reinventing the wheel, instead spending their
time with things that warrant their focus. Lua has a third-party Lua library that allows you to use
JSON in your Lua projects; this library can help encode or decode the information between the table
object and a JSON-encoded string, like so:
local json = require("json")
local theTable = {
title = "Learn Lua for iOS game development",
author = "Jayant Varma",
publisher = "Apress",
eBook = true,
year = 2012,
}
local resString = json.encode(theTable)
writeToFileSingle(restring,"mytable")
local readString = readFromFileSingle("mytable")
local resTable = json.decode(readString)
for k,v in pairs(resTable) do
print(k,v)
end
 
Search WWH ::




Custom Search