我創建使用處理持久性的高分小模塊它不工作Corona SDK JSON庫。
-- File name
local fileName = "highscore.json"
-- Path for File
-- The system.DocumentsDirectory will be backed up by synchronization in iOS
local pathForFile = system.pathForFile(fileName, system.DocumentsDirectory)
-- JSON library included in Corona SDK
local json = require("json")
-- This table holds two functions
-- persistHighscore, to save the highscore to file
-- fetchHighscore, to retrieve the saved highscore
local persistence = {}
-- Persists the highscore table
-- It receives only one parameter which must be a table
-- containing the highscore in a Key, Value pair
-- Example: {highscore = 10}
persistence.persistHighscore = function(highscoreTable)
local encoded = json.encode(highscoreTable)
local file, errorString = io.open(pathForFile, "w")
if not file then
print("Opening file failed: " .. errorString)
else
file:write(encoded)
file:flush()
file:close()
end
end
-- Returns the Highscore table
-- If there is a highscore file it will be read and a
--table containing the highscore will be returned
persistence.fetchHighscore = function()
local decoded, pos, msg = json.decodeFile(pathForFile)
if not decoded then
print("Decode failed at "..tostring(pos)..": "..tostring(msg))
else
print("File successfully decoded!")
return decoded
end
end
return persistence
在項目:
local persistence = require("highscorePeristence")
如果你不熟悉科羅娜SDK模塊加載和Lua一定要 檢查: Corona SDK API Doc - require 在您的高分數處理邏輯,當你發現分數高於目前的高分:
if score > highscore then
-- Container table to be stored in JSON
local scoreTable = {
highscore=score
}
persistence.persistHighscore(scoreTable)
end
而且wh您正在加載項目並且想要加載存儲的高分:
local highscore
local scoreTable = persistence.fetchHighscore()
-- No highscore was stored
if not scoreTable then
-- Initialize the highscore with 0 since there was no other value before
highscore = 0
else
-- Initialize the highscore with the value read from the JSON decoded table
highscore = scoreTable.highscore
end
使用[Simple-Table-Load-Save-Functions-for-Corona-SDK](https://github.com/robmiracle/Simple-Table-Load-Save-Functions-for-Corona-SDK) - 兩個非常簡單的加載和保存功能來存儲Lua表並將其讀回。需要Corona SDK JSON庫。 – ldurniat