尝试索引本地变量"f2"在Lua中出现错误。

我正在尝试编写一个游戏。我想将最高分写入文件,以便永久保存。 我尝试了下面的代码.. 但是我得到一个错误“尝试索引本地'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
点赞
用户107090
用户107090

f2nil,因为io.open失败了。可以使用以下方法查看错误信息:

local f2 = assert(io.open(path, "r"))

但是,请注意,之前调用的io.open已经破坏了您尝试读取的文件。

2014-10-29 11:46:00