Quick cocos2dx game Data Storage
Sort out several frequently used data formats in the project, and recommend GameState.
1: json Data Format
Json-> table
local str = json.encode({a=1,b=2,c={123}}) print(str)
Result {"a": 1, "c": [123], "B": "cc "}
Table-> json
local str2 = json.decode('{"a":1,"c":[123],"b":"cc"}')dump(str2)
Result
[LUA-print] - "" = {[LUA-print] - "a" = 1[LUA-print] - "b" = "cc"[LUA-print] - "c" = {[LUA-print] - 1 = 123[LUA-print] - }[LUA-print] - }
2: UserDefault-supports c ++ lua
Store Data
cc.UserDefault:getInstance():setIntegerForKey("Pass",1)--Integer,Double,Bool,Float,String,cc.UserDefault:getInstance():flush()
The UserDefault. xml file is generated in the writablePath.
Get Data
local user_integer = cc.UserDefault:getInstance():getIntegerForKey("Pass")
3: GameState is only used in the cocos2dx-Lua, often used in the project, you can perform encryption and decryption, formatting, storage table
(1) Import GameState
local GameState = import("framework.ui.utils.GameState")
(2) initialization
GameState. init (function (param) local returnValue = nil if param. errorCode then print ("error code ".. param. errorCode) else -- crypto if param. name = "save" then local str = json. encode (param. values) str = crypto. encryptXXTEA (str, "abcd") -- use the XXT encryption algorithm returnValue = {data = str} elseif param. name = "load" then local str = crypto. decryptXXTEA (param. values. data, "abcd") returnValue = json. decode (str) end return returnValue end, "data.txt", "abcd") --save It To The data.txt file under writablepathwith the encrypted password "abcd"
Import Data
GameData = GameState.load() or {}
Export to file
GameData.name = "uud"GameData.age = 10GameData.level = 15GameState.save(GameData)
4: FileUtils used in c ++ or lua
cc.FileUtils:getInstance():getString/ValueMap/IntegerFromFile(filePath)cc.FileUtils:getInstance():writeToFile(tb,filePath)
FilePath must be the path returned by cc. FileUtils: getInstance (): getWritablePath ().