I am using this method to save settings for my game
http://omnigeek.robmiracle.com/2012/02/23/need-to-save-your-game-data-in-corona-sdk-check-out-this-little-bit-of-code/
When should i use saveTabel and loadTable
If i use saveTable when the app starts it saves the default valeus of the table, but how can i load the last saved valeus when the app starts again.
Can i use( if )to check whether the file does exist or not ?
Some help please
Thanks in Advance!
You can use this in your main.lua:
--require the file with the save/load functions
local settings = require("settings")
myGameSettings = loadTable("mygamesettings.json")
if myGameSettings == nil then
--There are no settings. This is first time the user launch your game
--Create the default settings
myGameSettings = {}
myGameSettings.highScore = 1000
myGameSettings.soundOn = true
myGameSettings.musicOff = true
myGameSettings.playerName = "Barney Rubble"
saveTable(myGameSettings, "mygamesettings.json")
print("Default settings created")
end
Now if you want to save some new data to your settings:
--example: increment highScore by 50
myGameSettings.highScore = myGameSettings.highScore + 50
--example: change player name
myGameSettings.playerName = "New player name"
And to save the modified settings use:
saveTable(myGameSettings, "mygamesettings.json")
You can save settings everytime you change some data or you can save your settings just once: when the user tap exit game button.
You should load the file with default values and if file doesn't exist you should create it. and every time you change that value save you value in file.
Following code may help you:
function load_settings()
local path = system.pathForFile( "saveSettings.json", system.DocumentsDirectory )
local file = io.open( path, "r" )
if file then
local saveData = file:read( "*a" )
io.close( file )
local jsonRead = json.decode(saveData)
value = jsonRead.value
else
value = 1
end end
function save_settings()
local saveGame = {}
if value then
saveGame["value"] = value
end
local jsonSaveGame = json.encode(saveGame)
local path = system.pathForFile( "saveSettings.json", system.DocumentsDirectory )
local file = io.open( path, "w" )
file:write( jsonSaveGame )
io.close( file )
file = nil
end
Just call these functions for loading and saving the data. And it will be easier if you code these functions in different file and every time of loading and saving just require that file and use these functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With