游戏内再次封装saveFile和loadFile函数

原本的FILE模块更独立,不基于全局text变量和报错信息而是直接报错
This commit is contained in:
MrZ626
2021-11-25 17:38:09 +08:00
parent 720dc2131f
commit f3a88ef269
23 changed files with 206 additions and 111 deletions

View File

@@ -1,66 +1,60 @@
local fs=love.filesystem
local FILE={}
function FILE.load(name,mode)
function FILE.load(name,args)
if not args then args=''end
if fs.getInfo(name)then
local F=fs.newFile(name)
if F:open'r'then
local s=F:read()
F:close()
if mode=='luaon'or not mode and s:sub(1,6)=="return{"then
s=loadstring(s)
if s then
setfenv(s,{})
return s()
end
elseif mode=='json'or not mode and s:sub(1,1)=="["and s:sub(-1)=="]"or s:sub(1,1)=="{"and s:sub(-1)=="}"then
local res=JSON.decode(s)
if res then
return res
end
elseif mode=='string'or not mode then
return s
assert(F:open'r','open error')
local s=F:read()F:close()
if args:sArg'-luaon'or args==''and s:sub(1,6)=='return{'then
local func=loadstring(s)
if func then
setfenv(func,{})
local res=func()
return assert(res,'decode error')
else
MES.new("No file loading mode called "..tostring(mode))
error('decode error')
end
elseif args:sArg'-json'or args==''and s:sub(1,1)=='['and s:sub(-1)==']'or s:sub(1,1)=='{'and s:sub(-1)=='}'then
local res=JSON.decode(s)
if res then
return res
end
error('decode error')
elseif args:sArg'-string'or args==''then
return s
else
MES.new('error',name.." "..text.loadError)
error('unknown mode')
end
else
error('no file')
end
end
function FILE.save(data,name,mode)
if not mode then mode=""end
function FILE.save(data,name,args)
if not args then args=''end
if args:sArg'-d'and fs.getInfo(name)then
error('duplicate')
end
if type(data)=='table'then
if mode:find'l'then
if args:sArg'-luaon'then
data=TABLE.dump(data)
if not data then
MES.new('error',name.." "..text.saveError.."dump error")
return
error('encode error')
end
else
data=JSON.encode(data)
if not data then
MES.new('error',name.." "..text.saveError.."json error")
return
error('encode error')
end
end
else
data=tostring(data)
end
if mode:find'd'and fs.getInfo(name)then
MES.new('error',text.saveError_duplicate)
return
end
local F=fs.newFile(name)
F:open'w'
local success,mes=F:write(data)
F:flush()F:close()
if success then
return true
else
MES.new('error',text.saveError..(mes or"unknown error"))
MES.traceback()
end
assert(F:open('w'),'open error')
F:write(data)F:flush()F:close()
end
function FILE.clear(path)
if fs.getRealDirectory(path)==SAVEDIR and fs.getInfo(path).type=='directory'then

View File

@@ -205,15 +205,15 @@ end
Z.setOnQuit(destroyPlayers)
--Load settings and statistics
TABLE.cover (FILE.load('conf/user')or{},USER)
TABLE.cover (FILE.load('conf/unlock')or{},RANKS)
TABLE.update(FILE.load('conf/settings')or{},SETTING)
TABLE.coverR(FILE.load('conf/data')or{},STAT)
TABLE.cover (FILE.load('conf/key')or{},KEY_MAP)
TABLE.cover (FILE.load('conf/virtualkey')or{},VK_ORG)
TABLE.cover (loadFile('conf/user')or{},USER)
TABLE.cover (loadFile('conf/unlock')or{},RANKS)
TABLE.update(loadFile('conf/settings')or{},SETTING)
TABLE.coverR(loadFile('conf/data')or{},STAT)
TABLE.cover (loadFile('conf/key')or{},KEY_MAP)
TABLE.cover (loadFile('conf/virtualkey')or{},VK_ORG)
--Initialize fields, sequence, missions, gameEnv for cutsom game
local fieldData=FILE.load('conf/customBoards','string')
local fieldData=loadFile('conf/customBoards','-string')
if fieldData then
fieldData=STRING.split(fieldData,"!")
for i=1,#fieldData do
@@ -222,15 +222,15 @@ if fieldData then
else
FIELD[1]=DATA.newBoard()
end
local sequenceData=FILE.load('conf/customSequence','string')
local sequenceData=loadFile('conf/customSequence','-string')
if sequenceData then
DATA.pasteSequence(sequenceData)
end
local missionData=FILE.load('conf/customMissions','string')
local missionData=loadFile('conf/customMissions','-string')
if missionData then
DATA.pasteMission(missionData)
end
local customData=FILE.load('conf/customEnv')
local customData=loadFile('conf/customEnv')
if customData and customData['version']==VERSION.code then
TABLE.complete(customData,CUSTOMENV)
end

View File

@@ -15,6 +15,43 @@ local playSFX=SFX.play
--System
function loadFile(name,args)
if not args then args=''end
local res,mes=pcall(FILE.load,name,args)
if res then
return mes
else
if mes:find'open error'then
MES.new('error',text.loadError_open:repD(name))
elseif mes:find'unknown mode'then
MES.new('error',text.loadError_errorMode:repD(name,args))
elseif mes:find'no file'then
if not args:sArg'-canSkip'then
MES.new('error',text.loadError_noFile:repD(name))
end
elseif mes then
MES.new('error',text.loadError_other:repD(name,mes))
else
MES.new('error',text.loadError_unknown:repD(name))
end
end
end
function saveFile(data,name,args)
local res,mes=pcall(FILE.save,data,name,args)
if res then
return mes
else
MES.new('error',
mes:find'duplicate'and
text.saveError_duplicate:repD(name)or
mes:find'encode error'and
text.saveError_encode:repD(name)or
mes and
text.saveError_other:repD(name,mes)or
text.saveError_unknown:repD(name)
)
end
end
function isSafeFile(file,mes)
if love.filesystem.getRealDirectory(file)~=SAVEDIR then
return true
@@ -23,13 +60,13 @@ function isSafeFile(file,mes)
end
end
function saveStats()
return FILE.save(STAT,'conf/data')
return saveFile(STAT,'conf/data')
end
function saveProgress()
return FILE.save(RANKS,'conf/unlock')
return saveFile(RANKS,'conf/unlock')
end
function saveSettings()
return FILE.save(SETTING,'conf/settings')
return saveFile(SETTING,'conf/settings')
end
function applyLanguage()
text=LANG.get(SETTING.locale)
@@ -263,16 +300,16 @@ function setField(P,page)
end
end
end
function freshDate(mode)
if not mode then
mode=""
function freshDate(args)
if not args then
args=""
end
local date=os.date("%Y/%m/%d")
if STAT.date~=date then
STAT.date=date
STAT.todayTime=0
getItem('zTicket',1)
if not mode:find'q'then
if not args:find'q'then
MES.new('info',text.newDay)
end
saveStats()
@@ -475,7 +512,7 @@ function gameOver()--Save record
D.date=os.date("%Y/%m/%d %H:%M")
ins(L,p+1,D)
if L[11]then L[11]=nil end
FILE.save(L,('record/%s.rec'):format(M.name),'l')
saveFile(L,('record/%s.rec'):format(M.name),'-luaon')
end
end
end

View File

@@ -67,11 +67,19 @@ return{
switchSpawnSFX="Please turn on the block spawn SFX!",
needRestart="Restart to apply all changes",
loadError_errorMode="'$1' loading failed: no load mode '$2'",
loadError_read="'$1' loading failed: read failed",
loadError_noFile="'$1' loading failed no file:",
loadError_other="'$1' loading failed: $2",
loadError_unknown="'$1' loading failed: unknown reason",
saveError_duplicate="'$1' saving failed: duplicated filename",
saveError_encode="'$1' saving failed: encode failed",
saveError_other="'$1' saving failed: $2",
saveError_unknown="'$1' saving failed: unknown reason",
copyDone="Copied!",
saveDone="Data saved",
saveError="Failed to save:",
saveError_duplicate="Duplicated filename",
loadError="Failed to load:",
exportSuccess="Exported successfully",
importSuccess="Imported successfully",
dataCorrupted="Data corrupted",

View File

@@ -56,11 +56,19 @@ return{
switchSpawnSFX="Habilita los sonidos de aparición de las piezas ;)",
needRestart="Reinicia Techmino para que los cambios tengan efecto.",
-- loadError_errorMode="'$1' loading failed: no load mode '$2'",
-- loadError_read="'$1' loading failed: read failed",
-- loadError_noFile="'$1' loading failed no file:",
-- loadError_other="'$1' loading failed: $2",
-- loadError_unknown="'$1' loading failed: unknown reason",
-- saveError_duplicate="'$1' saving failed: duplicated filename",
-- saveError_encode="'$1' saving failed: encode failed",
-- saveError_other="'$1' saving failed: $2",
-- saveError_unknown="'$1' saving failed: unknown reason",
-- copyDone="Copied!",
saveDone="Datos guardados",
saveError="Error al guardar:",
saveError_duplicate="Archivo ya existente",
loadError="Error al cargar:",
exportSuccess="Exportado con éxito",
importSuccess="Importado con éxito",
dataCorrupted="Los datos están corruptos.",

View File

@@ -57,11 +57,19 @@ return{
switchSpawnSFX="Activez les effets sonores d'apparition des pièces pour jouer",
needRestart="Fonctionnera dès la prochaine partie",
-- loadError_errorMode="'$1' loading failed: no load mode '$2'",
-- loadError_read="'$1' loading failed: read failed",
-- loadError_noFile="'$1' loading failed no file:",
-- loadError_other="'$1' loading failed: $2",
-- loadError_unknown="'$1' loading failed: unknown reason",
-- saveError_duplicate="'$1' saving failed: duplicated filename",
-- saveError_encode="'$1' saving failed: encode failed",
-- saveError_other="'$1' saving failed: $2",
-- saveError_unknown="'$1' saving failed: unknown reason",
-- copyDone="Copied!",
saveDone="Données sauvegardées",
saveError="Sauvegarde échouée : ",
-- saveError_duplicate="Duplicate filename",
loadError="Lecture échouée : ",
exportSuccess="Exporté avec succès",
importSuccess="Importé avec succès",
dataCorrupted="Données corrompues",

View File

@@ -57,11 +57,19 @@ return{
switchSpawnSFX="Switch on spawn SFX to play",
needRestart="Funciona após reiniciar",
-- loadError_errorMode="'$1' loading failed: no load mode '$2'",
-- loadError_read="'$1' loading failed: read failed",
-- loadError_noFile="'$1' loading failed no file:",
-- loadError_other="'$1' loading failed: $2",
-- loadError_unknown="'$1' loading failed: unknown reason",
-- saveError_duplicate="'$1' saving failed: duplicated filename",
-- saveError_encode="'$1' saving failed: encode failed",
-- saveError_other="'$1' saving failed: $2",
-- saveError_unknown="'$1' saving failed: unknown reason",
-- copyDone="Copied!",
saveDone="Data Salva",
saveError="Falha ao salvar:",
-- saveError_duplicate="Duplicate filename",
loadError="Falha ao ler:",
exportSuccess="Exportado com sucesso",
importSuccess="Importado com sucesso",
dataCorrupted="Data corrompida",

View File

@@ -58,11 +58,19 @@ return{
ai_mission="X!!!",
needRestart="!!*#R#*!!",
loadError_errorMode="'$1' ↑x!: no load mode '$2'",
loadError_read="'$1' ↑x!: read failed",
loadError_noFile="'$1' ↑oading failed no file:",
loadError_other="'$1' ↑x!: $2",
loadError_unknown="'$1' ↑x!: unknown reason",
saveError_duplicate="'$1' ↓x!: duplicated filename",
saveError_encode="'$1' ↓x!: encode failed",
saveError_other="'$1' ↓x!: $2",
saveError_unknown="'$1' ↓x!: unknown reason",
-- copyDone="Copied!",
saveDone="~~~",
saveError="x!:",
saveError_duplicate="X←→X ?",
loadError="x!:",
exportSuccess="~Out~",
importSuccess="~In~",
dataCorrupted="XXXXX",

View File

@@ -67,11 +67,19 @@ return{
switchSpawnSFX="请开启方块出生音效",
needRestart="重新开始以生效",
loadError_errorMode="文件 '$1' 读取失败:无加载模式 '$2'",
loadError_read="文件 '$1' 读取失败:读取失败",
loadError_noFile="文件 '$1' 读取失败:没有文件",
loadError_other="文件 '$1' 读取失败:$2",
loadError_unknown="文件 '$1' 读取失败:原因未知",
saveError_duplicate="文件 '$1' 保存失败:文件已存在",
saveError_encode="文件 '$1' 保存失败:编码错误",
saveError_other="文件 '$1' 保存失败:$2",
saveError_unknown="文件 '$1' 保存失败:原因未知",
copyDone="复制成功!",
saveDone="保存成功!",
saveError="保存失败:",
saveError_duplicate="文件名重复",
loadError="读取失败:",
exportSuccess="导出成功",
importSuccess="导入成功",
dataCorrupted="数据损坏",

View File

@@ -67,11 +67,19 @@ return{
switchSpawnSFX="请打开繁殖特技效果",
needRestart="请重试以使更改生效",
loadError_errorMode="'$1' 加载失败:无加载模式 '$2'",
loadError_read="'$1' 加载失败:读取失败",
loadError_noFile="'$1' 加载失败:没有文件",
loadError_other="'$1' 加载失败:$2",
loadError_unknown="'$1' 加载失败:原因未知",
saveError_duplicate="'$1' 保存失败:文件名重复",
saveError_encode="'$1' 保存失败:编码失败",
saveError_other="'$1' 保存失败:$2",
saveError_unknown="'$1' 保存失败:原因未知",
copyDone="收到了!",
saveDone="保存的数据",
saveError="未能保存:",
saveError_duplicate="重复文件名",
loadError="未能加载:",
exportSuccess="成功导出",
importSuccess="导入成功",
dataCorrupted="数据损坏",

View File

@@ -67,11 +67,19 @@ return{
switchSpawnSFX="請開啟方塊生成音效",
needRestart="重新啟動以應用所有更改",
loadError_errorMode="檔案 '$1' 讀取失敗:無加載模式 '$2'",
loadError_read="檔案 '$1' 讀取失敗:讀取失敗",
loadError_noFile="檔案 '$1' 讀取失敗:沒有檔案",
loadError_other="檔案 '$1' 讀取失敗:$2",
loadError_unknown="檔案 '$1' 讀取失敗:原因未知",
saveError_duplicate="檔案 '$1' 保存失敗:檔案已存在",
saveError_encode="檔案 '$1' 保存失敗:編碼錯誤",
saveError_other="檔案 '$1' 保存失敗:$2",
saveError_unknown="檔案 '$1' 保存失敗:原因未知",
copyDone="拷貝成功!",
saveDone="保存成功!",
saveError="保存失敗:",
saveError_duplicate="文件名重複",
loadError="加載錯誤:",
exportSuccess="導出成功",
importSuccess="導入成功",
dataCorrupted="數據損壞",

View File

@@ -240,8 +240,8 @@ function NET.uploadSave()
{section=3,data=STRING.packTable(SETTING)},
{section=4,data=STRING.packTable(KEY_MAP)},
{section=5,data=STRING.packTable(VK_ORG)},
{section=6,data=STRING.packTable(FILE.load('conf/vkSave1'))},
{section=7,data=STRING.packTable(FILE.load('conf/vkSave2'))},
{section=6,data=STRING.packTable(loadFile('conf/vkSave1'))},
{section=7,data=STRING.packTable(loadFile('conf/vkSave2'))},
}..'}}')
MES.new('info',"Uploading")
end
@@ -282,13 +282,13 @@ function NET.loadSavedData(sections)
applyAllSettings()
TABLE.cover(NET.cloudData.keyMap,KEY_MAP)
success=success and FILE.save(KEY_MAP,'conf/key')
success=success and saveFile(KEY_MAP,'conf/key')
TABLE.cover(NET.cloudData.VK_org,VK_ORG)
success=success and FILE.save(VK_ORG,'conf/virtualkey')
success=success and saveFile(VK_ORG,'conf/virtualkey')
success=success and FILE.save(NET.cloudData.vkSave1,'conf/vkSave1')
success=success and FILE.save(NET.cloudData.vkSave2,'conf/vkSave2')
success=success and saveFile(NET.cloudData.vkSave1,'conf/vkSave1')
success=success and saveFile(NET.cloudData.vkSave2,'conf/vkSave2')
if success then
MES.new('check',text.saveDone)
end
@@ -460,7 +460,7 @@ function NET.updateWS_user()
if res.uid then
USER.uid=res.uid
USER.authToken=res.authToken
FILE.save(USER,'conf/user')
saveFile(USER,'conf/user')
if SCN.cur=='login'then
SCN.back()
end

View File

@@ -64,11 +64,11 @@ function scene.keyDown(key,isRep)
end
if key=="return2"or kb.isDown("lalt","lctrl","lshift")then
if #FIELD[1]>0 then
FILE.save(CUSTOMENV,'conf/customEnv')
saveFile(CUSTOMENV,'conf/customEnv')
loadGame('custom_puzzle',true)
end
else
FILE.save(CUSTOMENV,'conf/customEnv')
saveFile(CUSTOMENV,'conf/customEnv')
loadGame('custom_clear',true)
end
elseif key=="f"then
@@ -84,10 +84,10 @@ function scene.keyDown(key,isRep)
TABLE.clear(CUSTOMENV)
TABLE.complete(require"parts.customEnv0",CUSTOMENV)
for _,W in next,scene.widgetList do W:reset()end
FILE.save(DATA.copyMission(),'conf/customMissions')
FILE.save(DATA.copyBoards(),'conf/customBoards')
FILE.save(DATA.copySequence(),'conf/customSequence')
FILE.save(CUSTOMENV,'conf/customEnv')
saveFile(DATA.copyMission(),'conf/customMissions')
saveFile(DATA.copyBoards(),'conf/customBoards')
saveFile(DATA.copySequence(),'conf/customSequence')
saveFile(CUSTOMENV,'conf/customEnv')
sure=0
SFX.play('finesseError',.7)
BG.set(CUSTOMENV.bg)
@@ -123,7 +123,7 @@ function scene.keyDown(key,isRep)
do return end
::THROW_fail::MES.new('error',text.dataCorrupted)
elseif key=="escape"then
FILE.save(CUSTOMENV,'conf/customEnv')
saveFile(CUSTOMENV,'conf/customEnv')
SCN.back()
else
WIDGET.keyPressed(key)

View File

@@ -127,7 +127,7 @@ function scene.sceneInit()
page=1
end
function scene.sceneBack()
FILE.save(DATA.copyBoards(),'conf/customBoards')
saveFile(DATA.copyBoards(),'conf/customBoards')
end
function scene.mouseMove(x,y)

View File

@@ -16,7 +16,7 @@ function scene.sceneInit()
sure=0
end
function scene.sceneBack()
FILE.save(DATA.copyMission(),'conf/customMissions')
saveFile(DATA.copyMission(),'conf/customMissions')
end
local ENUM_MISSION=ENUM_MISSION

View File

@@ -16,7 +16,7 @@ function scene.sceneInit()
sure=0
end
function scene.sceneBack()
FILE.save(DATA.copySequence(),'conf/customSequence')
saveFile(DATA.copySequence(),'conf/customSequence')
end
local minoKey={

View File

@@ -96,7 +96,7 @@ local loadingThread=coroutine.wrap(function()
YIELD('loadMode')
for _,M in next,MODES do
M.records=FILE.load("record/"..M.name..".rec",'luaon')or M.score and{}
M.records=loadFile("record/"..M.name..".rec",'-luaon -canSkip')or M.score and{}
M.icon=M.icon and(modeIcons[M.icon]or gc.newImage("media/image/modeicon/"..M.icon..".png"))
end

View File

@@ -12,7 +12,7 @@ local function _login()
end
NET.wsconn_user_pswd(email,password)
if savePW then
FILE.save({email,password},'conf/account')
saveFile({email,password},'conf/account')
else
love.filesystem.remove('conf/account')
end
@@ -21,7 +21,7 @@ end
local scene={}
function scene.sceneInit()
local data=FILE.load('conf/account')
local data=loadFile('conf/account')
if data then
savePW=true
emailBox:setText(data[1])

View File

@@ -28,7 +28,7 @@ scene.widgetList={
NET.wsclose_user()
USER.uid=false
USER.authToken=false
FILE.save(USER,'conf/user')
saveFile(USER,'conf/user')
SCN.back()
end
else

View File

@@ -90,7 +90,7 @@ function scene.keyDown(key)
local rep=listBox:getSel()
if rep then
if rep.available and rep.fileName then
local repStr=FILE.load(rep.fileName,'string')
local repStr=loadFile(rep.fileName,'-string')
if repStr then
love.system.setClipboardText(love.data.encode('string','base64',repStr))
MES.new('info',text.exportSuccess)
@@ -108,7 +108,7 @@ function scene.keyDown(key)
local fileName=os.date("replay/%Y_%m_%d_%H%M%S_import.rep")
local rep=DATA.parseReplayData(fileName,fileData,false)
if rep.available then
if FILE.save(fileData,fileName,'d')then
if saveFile(fileData,fileName,'-d')then
table.insert(REPLAY,1,rep)
MES.new('info',text.importSuccess)
end

View File

@@ -71,7 +71,7 @@ scene.widgetList={
local D=_parseCB()
if D then
TABLE.update(D,VK_ORG)
FILE.save(VK_ORG,'conf/virtualkey')
saveFile(VK_ORG,'conf/virtualkey')
MES.new('check',text.importSuccess)
else
MES.new('error',text.dataCorrupted)

View File

@@ -23,7 +23,7 @@ function scene.sceneInit()
BG.set('none')
end
function scene.sceneBack()
FILE.save(KEY_MAP,'conf/key')
saveFile(KEY_MAP,'conf/key')
end
local forbbidenKeys={

View File

@@ -9,10 +9,10 @@ local snapUnit=1
local selected--Button selected
local function _save1()
FILE.save(VK_ORG,'conf/vkSave1')
saveFile(VK_ORG,'conf/vkSave1')
end
local function _load1()
local D=FILE.load('conf/vkSave1')
local D=loadFile('conf/vkSave1')
if D then
TABLE.update(D,VK_ORG)
else
@@ -20,10 +20,10 @@ local function _load1()
end
end
local function _save2()
FILE.save(VK_ORG,'conf/vkSave2')
saveFile(VK_ORG,'conf/vkSave2')
end
local function _load2()
local D=FILE.load('conf/vkSave2')
local D=loadFile('conf/vkSave2')
if D then
TABLE.update(D,VK_ORG)
else
@@ -37,7 +37,7 @@ function scene.sceneInit()
selected=false
end
function scene.sceneBack()
FILE.save(VK_ORG,'conf/virtualkey')
saveFile(VK_ORG,'conf/virtualkey')
end
local function _onVK_org(x,y)