【问题标题】:How to create and save settings in corona sdk?如何在 corona sdk 中创建和保存设置?
【发布时间】:2013-05-13 16:43:58
【问题描述】:

我正在使用这种方法来保存我的游戏设置

http://omnigeek.robmiracle.com/2012/02/23/need-to-save-your-game-data-in-corona-sdk-check-out-this-little-bit-of-code/

什么时候应该使用 saveTabel 和 loadTable

如果我在应用程序启动时使用 saveTable,它会保存表的默认值,但是当应用程序再次启动时,我如何加载最后保存的值。

我可以使用(if)来检查文件是否存在吗?

请帮忙

提前致谢!

【问题讨论】:

    标签: android ios coronasdk


    【解决方案1】:

    你可以在你的 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")
    

    您可以在每次更改某些数据时保存设置,也可以只保存一次设置:当用户点击退出游戏按钮时。

    【讨论】:

    • 将代码更新为 Lua 并添加了 require('settings') 行,假设 loadTable / saveTable 函数在 settings.lua 中
    【解决方案2】:

    您应该使用默认值加载文件,如果文件不存在,您应该创建它。 每次更改该值时,都会将值保存在文件中。

    以下代码可能对您有所帮助:

       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
    

    只需调用这些函数来加载和保存数据。如果您将这些函数编码在不同的文件中,并且每次加载和保存时只需要该文件并使用这些函数,就会更容易。

    【讨论】:

      【解决方案3】:

      通常您只需要在应用启动时加载您的设置。之后,该表在内存中,您只需在进行更改时保存该表,以便在应用程序重新启动后继续存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多