Ber*_*eri 5 android ios coronasdk
我正在使用此方法来保存我的游戏设置
我什么时候应该使用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")
您可以在每次更改某些数据时保存设置,也可以只保存一次设置:当用户点击退出游戏按钮时.
小智 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
只需调用这些函数即可加载和保存数据。如果您将这些函数编码在不同的文件中,并且每次加载和保存时只需要该文件并使用这些函数,那么会更容易。
| 归档时间: | 
 | 
| 查看次数: | 4826 次 | 
| 最近记录: |