new to Corona SDK, and i'm trying to figure out a way to load and save a file (which stores game data) on the simulator. (i dont want to have to debug on real device and take 15 seconds just to see a variable change each time).
i followed the tutorial on here: http://www.coronalabs.com/blog/2011/08/03/tutorial-exploring-json-usage-in-corona/ and couldn't find anything on stackoverflow that already addresses this issue.
right now i have the following code for reading and storing files:
local readJSONFile = function( filename, base )
-- set default base dir if none specified
if not base then base = system.ResourceDirectory; end
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
end
return contents
end
local writeToFile = function( filename, content )
-- set default base dir if none specified
if not base then base = system.ResourceDirectory; end
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "w" )
if file then
-- write all contents of file into a string
file:write( content )
io.close( file ) -- close the file after using it
end
end
it seems to work because i'll read my JSON file, save it with different data, load it, and that seems to persist. HOWEVER, as soon as i close my IDE, the changes are gone. Furthermore, my actual file on my system (mac book pro) is NOT changing.
if i do:
local json = require "json"
local wordsData = json.decode( readJSONFile( "trivia.txt" ) )
wordsData.someKey = "something different"
writeToFile("trivia.txt", json.encode( wordsData ) ) -- this only works temporarily
i'm reading my trivia.txt
file which is in the same directory as my main.lua
and attempt to change and load something. However, the above code will NOT make the actual change to the trivia.txt
on my mac book pro.
what's the proper way to do this?? i need to store game settings and game data (this is a trivia app, i need to store up to 50 words and what answer the user picked). I need to store the data in such a way that when i close my IDE, it'll remember what i wrote to file.
my guess is that when i load my trivia.txt
, it's actually looking at my mac book pro for that file, every time i load up my IDE. but then when i run it on my simulator the first time, it creates a new trivia.txt
in some temporary folder (which i have no idea where this is). and then it will start reading from there if i re-run the same code. right?
any help would be much appreciated!!! upvotes for more detailed answers, since i'm new to Corona SDK