Lua 保存到文件

我正在 Lua 上工作一个小项目,遇到了将得分保存到磁盘的问题。

我的代码如下,我确实得到了打印信息。

function saveHighScore(score)
    print("High score: "..tostring(score))
    local file = io.open("high_score.txt",'w')
    file:write(tostring(score))
    file:close()
end

有人可以帮忙吗?

点赞
用户870585
用户870585

我发现了问题。你不能将文件保存到资源目录,只能保存到文档目录中。

以下是修正后的代码:

function saveHighScore(score)
    path = system.pathForFile("highScore.txt", system.DocumentsDirectory)
    file = io.open(path,'w')
    file:write(tostring(score))
    io.close(file)
    print("High score: "..tostring(score))
    file = nil
end

我只是想把它发布出来,以防其他人遇到同样的问题并碰巧看到了这篇文章。

2015-06-26 08:29:39
用户3125367
用户3125367

如果你遵循前两条评论的建议,你可能会更快地解决问题。以下是解决方法,"以防其他人遇到同样的问题并发现了这篇文章":

function saveHighScore(score)
    print("High score: "..tostring(score))
    local file,err = io.open("high_score.txt",'w')
    if file then
        file:write(tostring(score))
        file:close()
    else
        print("error:", err) -- not so hard?
    end
end

http://www.lua.org/manual/5.3/manual.html#pdf-io.open:

io.open (filename [, mode])

此功能会以 mode 字符串中指定的方式打开文件。它返回一个新的文件句柄,或者在出现错误的情况下,返回 nil 和一个错误消息。

2015-06-26 16:57:45