我遇到了一个loadFile错误。Lua

我尝试将一个高分系统实现到我的游戏中,但是当我试着声明我的高分loadFile时,我得到了这个错误。

尝试调用全局变量 'loadFile'(一个空值)

这是我的代码。

highscore = loadFile("highscore.txt")

local function checkForFile()
    if highscore == "empty" then
        highscore = 0
        saveFile("highscore.txt", highscore)
    end
end
checkForFile()

print(" Highscore is", highscore)

local function onSystemEvent()
    if playerScore > tonumber(highscore) then
        -- 当加载时,我们使用 tonumber 转换为数字字符串
        saveFile("highscore.txt", score)
    end
end
Runtime: addEventListener(“system”,onSystemEvent)

我使用的是Corona SDK。

点赞
用户1955931
用户1955931

开发者发布了一份不错的指南关于如何保存和写入文件,你可以从这里获取。

基本上你可以通过 system.pathForFile 获取文件路径,然后使用 io.open 打开它。

你可以这么做:

local path = system.pathForFile( "highscore.txt", system.DocumentsDirectory )
local file = io.open(path, 'w+')

然后,获取文件内容:

local content = file:read('*a')
local highscore

if (content ~= null)
    highscore = tonumber(content)
    // 做一些已加载的高分数操作
end

并且写入文件:

file:write(highscore)
2014-04-22 00:09:38
用户869951
用户869951

提示

你正在加载的文件不是 Lua 文件,而是文本文件。因此,即使存在 loadfile,使用它也没有意义。相反,使用 io.read 结合 file:readfile:lines (其中 fileio.open() 返回的对象)。

## 提示
你正在加载的文件不是 Lua 文件,而是文本文件。因此,即使存在 `loadfile`,使用它也没有意义。相反,使用 `io.read` 结合 `file:read` 或 `file:lines` (其中 `file` 是 `io.open()` 返回的对象)。
2014-04-22 00:15:10