File io 在lua中保存高分的问题
(这是关于上一个问题) 基本上,我正在尝试用lua构建一个游戏(这是我第一次玩游戏) 但是,我无法将highscore保存到文件中。如果它被保存,那么我就无法检索它们。(简而言之,我总是在执行代码时遇到一些或其他错误/问题 请看一下上面的代码。我想同时显示高分和当前分数。当前分数显示得非常完美。这是我昨天晚上尝试过的。但现在,高分没有保存在文件中。(即,最好的总是显示0)。此外,cmd说“无法从scoredata.txt读取分数”我找不到哪里出错了 请帮忙做这个? 请告诉我哪里出错了?File io 在lua中保存高分的问题,file-io,permissions,lua,coronasdk,File Io,Permissions,Lua,Coronasdk,(这是关于上一个问题) 基本上,我正在尝试用lua构建一个游戏(这是我第一次玩游戏) 但是,我无法将highscore保存到文件中。如果它被保存,那么我就无法检索它们。(简而言之,我总是在执行代码时遇到一些或其他错误/问题 请看一下上面的代码。我想同时显示高分和当前分数。当前分数显示得非常完美。这是我昨天晚上尝试过的。但现在,高分没有保存在文件中。(即,最好的总是显示0)。此外,cmd说“无法从scoredata.txt读取分数”我找不到哪里出错了 请帮忙做这个? 请告诉我哪里出错了? 另外,如
另外,如果可能,请提供(或编辑)正确的代码?这一行似乎有问题
function saveScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local score=get_score() --The get_score() returns the value of current score which is saved in 'score'.
local newScore = compareScore()
local contents = tostring( newScore )
file:write( contents )
io.close( file )
return true
else
print("Error: could not write Score")
return false
end
end
function loadScore()
local path = system.pathForFile("scoredata001.txt", system.DocumentsDirectory)
local contents = ""
local file = io.open( path, "r" )
if file then
local contents = file:read( "*a" )
local score = tonumber(contents);
io.close( file )
return score
end
print("Could not read scores from scoredata.txt")
return nil
end
function return_highScore()
local highscore=loadScore()
if highscore==nil then
highscore=0
end
return highscore
end
function compareScore()
local highscore=return_highScore()
if highscore then
local currscore=get_score()
if highscore==0 then
return highscore
elseif currscore>highscore then
return currscore
end
end
return true
end
function disp_permScore()
local display_score=return_highScore()
text_display2= display.newText("GAME OVER!\n BEST: " ..display_score, 0, 0, "Helvetica", 80)
text_display2.x = centerX
text_display2.y = centerY
text_display2.alpha=1
function gameOver()
mainScreen()
saveScore()
disp_permScore()
end
这意味着您检查高分是否为0,如果是,则返回它,而不是实际的高分
另外,我不知道您的代码是否只是粘贴错误,但如果不缩进代码,阅读起来会非常困难。请再试一次,我将代码缩进,现在很容易发现错误。+1关于缩进。事实上,代码甚至在语法上都不有效(在靠近结尾的地方缺少一个
结尾
)。正确的缩进会使这一点变得明显。这也是对试图阅读和理解代码的人的礼貌……非常感谢您缩进代码。当我运行代码时,corona模拟器输出显示“无法从scoredata.txt读取分数”意味着loadScore()会闪烁此错误函数。我添加了assert函数,错误闪现为“Permission denied”。怎么办?这可能有很多问题。您是否检查了文件是否存在?否则,我最好的建议是将代码更改为使用JSON。这样,您可以创建一个变量,并像这样使用:“highscores.currentScore”和highscore.highestScore.阅读此文-还记得通过单击答案旁边的小“v”或“批准”标记来接受问题的答案。非常感谢@Frozire在我的代码上花费的时间和精力。我在没有JSON的情况下成功保存了highscore。感谢您的帮助:)
if highscore==0
then
return highscore