hey wp sorry for the delay, this is what i do for my game and its working pretty good, i will try to explain step by step the best i can:
myGameSettings = {} --"I create a new table that i will eventually save into a .json file" myGameSettingsOut={} --"I create an auxiliar table, that will READ from the file, to compare the current highscore with the new score" myGameSettings.highScore = globals.score --"I asign my score (global cause it came from another scene) to the table" if loadTable("mygamesettings.json") then --"This will control if the .json file already exist" myGameSettingsOut = loadTable("mygamesettings.json")--"Here i read the already existent file" if (myGameSettings.highScore \> myGameSettingsOut.highScore) then --"Comparation between new score and current highscore" saveTable(myGameSettings, "mygamesettings.json") --"If the new is bigger i save the table into the .json (overwriting the existing one)" local txt=display.newText("display new besthigh"..myGameSettings.highScore) group:insert(txt) else local txt = display.newText( "Best: "..myGameSettingsOut.highScore) --"I just print the current highscore if the new score is not bigger" group:insert(txt) end else --"If the .json file doesnt exist(first time i execute the code probably)" saveTable(myGameSettings, "mygamesettings.json") --" I just save the new score into the higscore since theres nothing to compare" local txt = display.newText( "New Best: "..myGameSettings.highScore) group:insert(txt) end
There is my code, i tried to explain what everything does there after the --, i hope you understand it now, of course for it to work u need to have these functions somewhere in your scene
local json = require ("json") function saveTable(t, filename) -- Function to save a table into a json file 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 loadTable(filename) -- Function to load a table from a json file 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 return nil end
Just copy paste them if you dont wanna understand them
and i suggest you to save those two cause you will probably need them everytime you work with external files (save scores, save settings like volumen, or username, etc)
I hope its a bit more clear now and i hope thats what you need. Did you fixed the score getting back to 0?
Edit: the display.newText things from my piece of code wont work probably cause i shortened them to fit in here, but im sure u know how to display text 