2014-10-29 78 views
0

我试图编写游戏。我想将高分写入文件以永久保存。 我试了下面的代码..但后来我得到一个错误“尝试索引本地'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 

回答

2

f2是零,因为io.open失败。使用此看到错误消息:

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

但是,请注意,以io.open以前的调用而被破坏你试图读取该文件。

+0

它说“权限被拒绝”..如何纠正这个问题? – Ozitrick 2014-10-29 11:52:32

+1

@TimeThief,你走了。检查路径和权限。不是一个Lua问题,真的。 – lhf 2014-10-29 11:54:41

+0

如何检查?我的意思是我在代码中添加了'local path = system.pathForFile(“scoredata.txt”,system.DocumentsDirectory)'.. – Ozitrick 2014-10-29 12:13:01