I have a function that is supposed to create a json file in system.DocumentsDirectory to save level scores to if it doesn’t exist, and if the file is already created to write over it with new correct level info if new levels were added after the file’s initial creation.
engine\_score["build"] = function() local ifscores = jcodec["exist"]("scores.json") local scorecard local readcard scorecard = { db = {} } if(ifscores==0)then jcodec["write"]("scores", scorecard) end readcard = jcodec["read2"]("scores.json", "db", "save") for i=1, #resLib["masterLib"]["map"] do if(readcard[i] == nil)then scorecard["db"][i] = 0 elseif(readcard[i] ~= nil)then scorecard["db"][i] = readcard[i] end composer.setVariable("ep" .. i .. "scr" , scorecard[i]) end jcodec["write"]("scores", scorecard) end
file writing function:
jcodec["write"] = function(fname, ftable) local savedData = ftable local tpath = fname .. ".json" local path = system.pathForFile(tpath, system.DocumentsDirectory) local file, err = io.open(path, "w") print(err) savedData = json.encode(ftable) file:write(savedData) io.close(file) file=nil end
If scores.json doesn’t exist in the folder, the functions doesn’t give any errors. However, if scores.json already exists, I get an error from the write function for the line:
file:write(savedData)
The error claims that ‘file’ is nil. I tried printing err for setting file to io.open the path. The path is correct but err said that ‘Permission Denied’ to write to that file even though it exists and the path is correct. I tried opening it with “r+”, “w+” but that didn’t work either. So the error is occuring when I try to write, but the actual problem is I can’t open the file for the purpose of writing, only reading. I am definitely closing the file every time after using it.
I tried to debug this as best I could but I have no idea what is wrong. My write function is more or less identical to the example code except I convert the table to json before trying to write the file. Removing that line didn’t change anything either.
I tried moving the write function right before the ‘read2’ function and still the same effect.
Basically once the file is created, I can’t write to it. I can’t write over it with updated data. I don’t know how to proceed.