[英]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.