I am attempting to save elements of my game the standard way, by encoding to JSON, saving to a file, and decoding the file to load the table later. However, this does not seem to work for 2D arrays. I am testing this in the Android Corona Simulator.
My map data is a 2D array of information such as type, image filename, boolean flags, etc…
When I try to save and load the table, the indexing is corrupted slightly.
This works:
local saveGame = {} saveGame = mapData print(saveGame[1][1].type) utility.saveTable(saveGame, "saveGame.json") print(saveGame[1][1].type) saveGame = utility.loadTable("saveGame.json") print(saveGame["1"][1].type)
This doesn’t:
local saveGame = {} saveGame = mapData print(saveGame[1][1].type) utility.saveTable(saveGame, "saveGame.json") print(saveGame[1][1].type) saveGame = utility.loadTable("saveGame.json") print(saveGame[1][1].type) --Crash here - "attempt to index field '?' (a nil value)"
The load/save functions I’m using are Rob Miracle’s utilities from here.
function M.saveTable(t, filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local file = io.open(path, "w") if file then local contents = json.encode(t) file:write( contents ) io.close( file ) return true else return false end end function M.loadTable(filename) local path = system.pathForFile( filename, system.DocumentsDirectory) local contents = "" local myTable = {} local file = io.open( path, "r" ) if file then local contents = file:read( "\*a" ) myTable = json.decode(contents); io.close( file ) return myTable end print(filename, "file not found") return nil end
Any ideas for how to fix this? I’m considering saving/loading each array of the 2D array separately, or creating a custom parser for the corrupted JSON, but I figure there must be a better solution.