整理一下项目中经常用到的几种数据格式,推荐GameState
1:json数据格式
json->table
local str = json.encode({a=1,b=2,c={123}})
print(str)
结果 {“a”:1,”c”:[123],”b”:”cc”}
table->json
local str2 = json.decode('{"a":1,"c":[123],"b":"cc"}')
dump(str2)
结果
[LUA-print] - "<var>" = {
[LUA-print] - "a" = 1
[LUA-print] - "b" = "cc"
[LUA-print] - "c" = {
[LUA-print] - 1 = 123
[LUA-print] - }
[LUA-print] - }
2: UserDefault - -支持c++ lua 语言
存储数据
cc.UserDefault:getInstance():setIntegerForKey("Pass",1)
--Integer,Double,Bool,Float,String,cc.UserDefault:getInstance():flush()
在writablePath路径下会生成UserDefault.xml文件
获取数据
local user_integer = cc.UserDefault:getInstance():getIntegerForKey("Pass")
3 : GameState 只有在cocos2dx-Lua下使用,经常在项目中使用,可以进行加解密、格式化、存储table
(1)导入GameState
local GameState = import("framework.ui.utils.GameState")
(2)初始化
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")--使用XXT加密算法
returnValue = {data = str}
elseif param.name == "load" then
local str = crypto.decryptXXTEA(param.values.data,"abcd")
returnValue = json.decode(str)
end
end
return returnValue
end,"data.txt","abcd") --保存到writablePath下data.txt文件中,加密口令"abcd"
导入数据
GameData = GameState.load() or {}
导出到文件
GameData.name = "uud"
GameData.age = 10
GameData.level = 15
GameState.save(GameData)
4:FileUtils 在 c++ 或者lua中使用
cc.FileUtils:getInstance():getString/ValueMap/IntegerFromFile(filePath)
cc.FileUtils:getInstance():writeToFile(tb,filePath)
filePath 一定是 cc.FileUtils:getInstance():getWritablePath()返回的路径