我正在使用此方法保存游戏设置
我何时应该使用saveTabel和loadTable
如果我在应用程序启动时使用saveTable,它会保存表的默认值,但是如何在应用程序再次启动时加载上次保存的valeus。
我可以使用(if)检查文件是否存在吗?
请帮忙
提前致谢!
答案 0 :(得分:7)
您可以在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
现在,如果您想将一些新数据保存到您的设置中:
--example: increment highScore by 50
myGameSettings.highScore = myGameSettings.highScore + 50
--example: change player name
myGameSettings.playerName = "New player name"
要保存修改后的设置,请使用:
saveTable(myGameSettings, "mygamesettings.json")
您可以在每次更改某些数据时保存设置,也可以只保存一次设置:当用户点按退出游戏按钮时。
答案 1 :(得分:4)
您应该使用默认值加载文件,如果文件不存在,您应该创建它。 每次更改该值时,请保存文件中的值。
以下代码可以帮助您:
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
只需调用这些函数即可加载和保存数据。如果您在不同的文件中编写这些函数并且每次加载和保存时只需要该文件并使用这些函数,就会更容易。
答案 2 :(得分:1)
通常,您只需在应用启动时加载设置即可。之后,该表位于内存中,您只需在进行应用程序重启后需要进行的更改时保存该表。