我正在尝试编写游戏代码。我想将高分写入文件以永久保存。 我尝试了下面的代码..但后来我得到一个错误“尝试索引本地'f2'(一个零值)” 如何纠正这个错误? 另外..我尝试了许多其他组合来写新的高分给文件..但每次我遇到一些或其他问题:/。 (这也是我认为应该工作的东西)。如果不是这样,那么有人可以提供给我编写新分数到文件的代码以及在游戏结束时检索数据。
代码:
local path = system.pathForFile( "scoredata.txt", system.DocumentsDirectory )
function read_score()
local f1 = io.open (path, "w")
local f2 = io.open(path, "r")
highScore = f2:read( "*n" )
if highScore==nil -- Initial value of score is 0 and "score" is the in-game score counter.
then highScore=0
end
if score>highScore
then
highScore=score
f1:write(highScore)
disp_permScore()
else
disp_permScore()
end
io.close(f1)
io.close(f2)
end
function disp_permScore() -- Function to display the highscore
text_display2= display.newText("BEST: " .. highScore, 0, 0, "Helvetica", 90)
text_display2.x = centerX
text_display2.y = centerY + 80
text_display2.alpha=1
end
function gameOver() --this function is invoked after game is over
read_score()
local bg= display.newImage("bgpng.png")
end
答案 0 :(得分:2)
f2
为零,因为io.open
失败了。使用此选项可查看错误消息:
local f2 = assert(io.open(path, "r"))
但请注意,之前对io.open
的调用会破坏您尝试阅读的文件。