学到一点更新一点,持续更新
1、cocos2dx-lua中对文件的操作都用cc.FileUtils这个类进行操作,它是单一实例。
(1)获取可写目录:local docpath = cc.FileUtils:getInstance():getWritablePath().."hero.txt"
打印出docpath 为C:\Users\Administrator\Desktop\allience(具体的目录)
(2)判断文件是否存在:local isexit = cc.FileUtils:getInstance():isFileExist(docpath)
(3)读取具体目录文件里面的数据:local str = cc.FileUtils:getInstance():getStringFromFile(docpath)
2、使用JSON数据存储。
(1)json字符串解码
local docpath = cc.FileUtils:getInstance():getWritablePath().."hero.txt"
获取docpath目录文件里的数据:local str = cc.FileUtils:getInstance():getStringFromFile(docpath)
打印出来的str为[{"zhiwei":1,"kuzi":0,"id":6,"yifu":0,"xianglian":0,"xiezi":0,"wuqi":0,"shoutao":0,"level":1,"jinyan":5}]大概意思就是一个key对应一个value,打印的str即是hero.text文件里面的数据,如下图
local herodadta = {}
herodadta = json.decode(str)
打印出来的herodata数据如下面数据格式,具体如下图(只注意数据格式即可)
herodata= { {zhiwei = 1 , id = 6,level = 1, jinyan = 5,yifu = 0,wuqi = 0,kuzi = 0,shoutao = 0,xianglian = 0,xiezi = 0} }
(2)json字符串编码
首先有如下数据
herodata = { {zhiwei = 1 , id = 6,level = 1, jinyan = 5,yifu = 0,wuqi = 0,kuzi = 0,shoutao = 0,xianglian = 0,xiezi = 0} }
local str = json.encode(herodata )
打印出来的str数据如下
str= [{"zhiwei":1,"kuzi":0,"id":6,"yifu":0,"xianglian":0,"xiezi":0,"wuqi":0,"shoutao":0,"level":1,"jinyan":5}]
将str写入hero.text中
local docpath = cc.FileUtils:getInstance():getWritablePath().."hero.txt"
local f = assert(io.open(docpath, 'w'))
f:write(str)
(3)使用UserDefault数据存储
原型:存储:cc.UserDefault:getInstance():setIntegerForKey(key,value)
获取:cc.UserDefault:getInstance():getIntegerForKey(key)
游戏中每个玩家的ID都不一样,所以根据id存储数
cc.UserDefault:getInstance():setIntegerForKey("wearequip"..self.playerId,10)
local sign= cc.UserDefault:getInstance():getIntegerForKey("wearequip"..self.playerId)
sign = 10,相当于新建一个表{“wearequipself.playerId ”= 10},然后通过表的key获取value
存储数据类型有如下几种
bool类型:cc.UserDefault:getInstance():setBoolForKey(key, value)
cc.UserDefault:getInstance():getBoolForKey(key)
int类型:cc.UserDefault:getInstance():setIntegerForKey(key, value)
cc.UserDefault:getInstance():getIntegerForKey(key)
string类型:cc.UserDefault:getInstance():setStringForKey(key, value)
cc.UserDefault:getInstance():getStringForKey(key)
float类型: cc.UserDefault:getInstance():setFloatForKey(key, value)
cc.UserDefault:getInstance():getFloatForKey(key)
double类型:cc.UserDefault:getInstance():setDoubleForKey(key, value)
cc.UserDefault:getInstance():getDoubleForKey(key)