卡在Lua的I/O操作中。

我正在尝试用lua设计一款游戏(这是我的第一款游戏,因为我对这种语言是新手)。

好的......所以我已经有了一个计分器,它在屏幕上点击时会加上+1。我想做的是永久保存最高分数。

我想将最高分数(在这种情况下为“30”)单独显示在屏幕上。这就是我卡住的地方。我尝试了一下I/O库,但这使事情变得更加复杂了。

有人可以帮我吗?

这是我尝试的内容:

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

function gameOver()
disp_tempscore()

if score>highScore    -- 这里highScore的初始值为0
    then
    highScore=score
io.write (highScore)
end

score=0     -- 这将得分变为0。(有一个单独的计分器来计算分数并存储在“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:”的得分出现了最高分,但只有在多次运行同一时间时才会出现。

我的意思是,当我在corona模拟器中启动游戏并玩5次游戏(假设),最高得分显示正确的数据。但是,当我退出模拟器并重新启动它时,最高得分消失并显示为0。

如何永久存储数据(在这种情况下为得分)?

EDIT: (这是我上次尝试的内容(我尝试过的其中一个建议))

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

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

点赞
用户869951
用户869951

我认为问题在于你从未将分数写入得分文件:

io.write (highScore)

应该是

f1:write(highScore)

并且当你不再需要文件时,应该尽快关闭文件(例如,防止数据丢失)。此外,不要忘记按照 Corona 文档所述使用 system.pathForFile(filename,system.DocumentsDirectory),这样文件将被放置在正确的位置。

2014-10-27 19:29:31
用户4180354
用户4180354

你正在不正确地使用 file:read() 函数。它需要一个“option”参数并返回它读取的内容。因此,

f1:read(highScore)

应该是

highScore = f1:read("*n")

其中 "*n" 参数表示您要读取一个数字。

编辑:

为了避免文件写入/读取不正确的问题,请尝试以下(未经测试)代码:

if score > highScore then
    highScore = score
    local f1 = io.open(path, "w") -- 以写入模式打开文件以擦除内容
    f1:write(highScore)           -- 写入新的最高分数
    f1:close()                    -- 关闭文件
end

进行写入,以及

local f1 = io.open(path, "r")     -- 以读取模式打开文件
highScore = f1:read("*n")         -- 读取保存的最高分数

if highScore == nil then          -- 如果无法读取最高分数
    --此处放置错误代码(例如将高分数设置为0、通知用户等)
end

f1:close()                        -- 关闭文件

进行读取。

2014-10-28 16:08:07