After that, we can use file:read() to retrieve them.
However, the game setting data are recorded in table format in most cases.
The functions file:write() and file:read() are both accepted string type as the input/output.
We need to use json to encode table into string and decode string into table, as shown below:
local json = require("json") function saveTable(myTable, filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local file = io.open(path, "w") if file then local sTable = json.encode(myTable)--encode the table to string file:write( sTable ) io.close( file ) return true else return false end end function loadTable(filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local contents = "" local myTable = {} local file = io.open( path, "r" ) if file then local sTable = file:read( "*a" )-- read the entire contents of the file myTable = json.decode(sTable)--decode the string back to table io.close( file ) file = nil return myTable end return nil end
Next, how to use the above functions in our codes?
gameSettingsFileName = "mygamesettings.json" currentSettingsVersion = 3 myGameSettings = loadTable("mygamesettings.json") if(myGameSettings == nil or myGameSettings.version == nil or myGameSettings.version ~= currentSettingsVersion) then -- the default settings myGameSettings = {} myGameSettings.version = currentSettingsVersion myGameSettings.level = 2 myGameSettings.speed = 5 saveTable(myGameSettings, gameSettingsFileName) end myGameSettings.level = myGameSettings.level+1 saveTable(myGameSettings, gameSettingsFileName)