本文已参与「新人创作礼」活动,一起开启掘金创作之路。 我这边遇到一个简单的需求
`local LocalConfig={} --PS.里面的值不要设置nil--
LocalConfig.PlayerConfig={} --玩家配置--
function LocalConfig.ReadConfig() LocalConfig.PlayerConfig=LocalConfig.DefaultConfig local T={} if cc.FileUtils:getInstance():isFileExist(getConfigPath()) then local pFile = io.open(getConfigPath(),"r") local Data = pFile:read("*all") pFile:close() T=loadstring(Data)() if type(T)=="table" then dump(T) LocalConfig.PlayerConfig=T end end end
function LocalConfig.Save() LocalConfig.WriteConfig(LocalConfig.PlayerConfig) end
function LocalConfig.WriteConfig(T) Save=function(O,pFile,ISChildT) ISChildT=ISChildT or false if type(O)=="number" then pFile:write(O) elseif type(O)=="string" then pFile:write(string.format("%q",O)) elseif type(O)=="boolean" then pFile:write(tostring(O)) elseif type(O)=="table" then if ISChildT then pFile:write("{") else pFile:write("{\n") end for K,V in pairs(O) do if type(K)=="number" then pFile:write("[",K,"]=") else pFile:write("["",K,""]=") end Save(V,pFile,type(V)=="table") if ISChildT then pFile:write(",") else pFile:write(",\n") end end if ISChildT then pFile:write("}") else pFile:write("}\n") end else error("CAN'T SERIALIZE WHICH TYPE IS " ..type(O)) end end local pFile=io.open(getConfigPath(),"w") pFile:write("return") Save(T,pFile) pFile:close() end
function LocalConfig.getValue(Key) if LocalConfig.PlayerConfig[Key]~=nil then return LocalConfig.PlayerConfig[Key] else return LocalConfig.DefaultConfig[Key] end end
function LocalConfig.setValue(Key,Value) LocalConfig.PlayerConfig[Key]=Value end
local function getConfigPath() return string.format("%s%sConfig",cc.FileUtils:getInstance():getWritablePath(),getUniqueKey()) end
function getUniqueKey()
return tostring(用户ID) .. tostring(角色名) .. "V3.7"
end`
这个适合一个玩家多个角色的数据保存,只是demo而已,提供思路而已
LocalConfig.SetValue("auto_skill")
local value = LocalConfig.getValue("auto_skill")