[英]How to create and save settings in corona sdk?
我正在使用此方法来保存我的游戏设置
我什么时候应该使用saveTabel和loadTable
如果我在应用程序启动时使用saveTable,它将保存表的默认值,但是如何在应用程序再次启动时加载上次保存的valeus。
我可以使用(if)检查文件是否存在吗?
请帮忙
提前致谢!
你可以在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")
您可以在每次更改某些数据时保存设置,也可以只保存一次设置:当用户点击退出游戏按钮时。
您应该使用默认值加载文件,如果文件不存在,您应该创建它。 每次更改该值都会保存文件中的值。
以下代码可以帮助您:
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
只需调用这些函数即可加载和保存数据。 如果您在不同的文件中编写这些函数并且每次加载和保存时只需要该文件并使用这些函数,就会更容易。
通常,您只需在应用启动时加载您的设置。 之后,该表位于内存中,您只需在进行应用程序重启后需要进行的更改时保存该表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.