在lua中坚持I / O操作

时间:2014-10-26 18:01:46

标签: lua file-handling

我正在尝试用lua设计一款游戏(这是我的第一款游戏,因为我对这种语言不熟悉) 好吧..所以我运行了一个分数计数器,在屏幕上点击加了+1。 我想做的是我想永久保存高分。

我想在屏幕上单独显示高分(在这种情况下为'30')。这就是我被困住的地方。 我尝试使用I / O库进行调整,但这使事情变得更复杂。 有人可以帮我这个吗?

这就是我的尝试:

local f1 = io.open ("scoredata.txt", "a")

function gameOver()  
disp_tempscore()

if score>highScore    -- Here initial value of highScore was 0
    then
    highScore=score
io.write (highScore)
end  

score=0     -- This turns the score 0. (There is a separate score counter that counts the score and stores in 'score')

mainScreen()
local f2 = io.open ("scoredata.txt", "r")
if f2~= nil
then
save_high = io.read(highScore)

end
    text_display2= display.newText("BEST : " .. highScore, 0, 0, "Helvetica", 90)
    text_display2.x = centerX
    text_display2.y = centerY + 80
    text_display2.alpha=1 

现在,“BEST:”的分数似乎是最高分,但仅适用于同时进行的多次分数。 我的意思是当我在电晕模拟器中开始游戏并玩游戏5次(假设)时,最高分显示正确的数据。 但是,当我退出模拟器并重新启动它时,最高分会消失并显示0。 如何永久存储数据(在这种情况下得分)?

编辑:(这是我上次尝试过的(我试过的一次点击))

local function disapp (event)                   -- An event listener that responds to "tap"

local obj = event.target
display.remove (obj)

audio.play(sound)

transition.cancel (event.target.trans)

score=score+1
curr_scoreDisp = score
scoreText.text=score

local f1 = io.open (path, "a")   --Writing score to file
if score>highScore  -- Initial value of highScore is 0
    then
    highScore=score
    f1:write(highScore)
end
io.close(f1)

然后:

local function disp_Permscore()
local f1 = io.open (path, "r")

f1:read(highScore)
    text_display2= display.newText("BEST : " .. highScore, 0, 0, "Helvetica", 90)
    text_display2.x = centerX
    text_display2.y = centerY + 80
    text_display2.alpha=1 
    io.close(f1)
end

这是另一个从文件读取分数然后显示它的函数。 现在?这有助于以任何方式纠正问题吗?

2 个答案:

答案 0 :(得分:0)

我认为问题在于你永远不会写入乐谱文件:

io.write (highScore)

应该是

f1:write(highScore)

并且您应该在不再需要时立即关闭该文件(例如,防止因崩溃而丢失数据)。另外,请不要忘记使用电晕文档中描述的system.pathForFile( filename, system.DocumentsDirectory),因此文件放在正确的位置。

答案 1 :(得分:0)

您未正确使用file:read()功能。它需要一个'选项'参数并返回它所读的内容。因此,

f1:read(highScore)

应该是

highScore = f1:read("*n")

其中"*n"参数指定您要读取数字。

修改

为防止文件无法正确写入/读取,请尝试以下(未经测试)代码:

if score > highScore then
    highScore = score
    local f1 = io.open(path, "w") -- opening in write mode erases content
    f1:write(highScore)           -- write the new highscore
    f1:close()                    -- close the file
end

写作,

local f1 = io.open(path, "r")     -- open the file in read mode
highScore = f1:read("*n")         -- read the saved highscore

if highScore == nil then          -- if the highscore could not be read
    --error code here (e.g. set highscore to 0, notify the user, etc.)
end

f1:close()                        -- close the file

阅读。