0

我有这个错误:

尝试连接全局“高分”(一个nil值)

这就是我在 Game.lua 文件中检查高分的方式:

function HighscoreUpdate()
    if(score>Highscore)then
        Highscore = score
    end
end

这就是我将 Highscore 保存在 score.txt 中的方式,并在所有 CollisionChecks 之后调用它(我在这里没有任何错误):

    function savescore(hs)
        local path = system.pathForFile( "score.txt", system.DocumentsDirectory )

        local file = io.open ( path, "w" )

        local contents = tostring(hs)
        file:write( contents )

        file:close( ) 
    end

这就是我尝试加载它的方式(我认为这是问题所在):

    loadScores = function()
    local scores = {}
    local str = ""
    local n = 1

    local path = system.pathForFile( "score.txt", system.DocumentsDirectory )

    local file = io.open ( path, "r" ) 
    if file == nil then 
        return 0
    end


    local contents = file:read( "*a" )
    file:close() 

    for i = 1, string.len( contents ) do
        local char = string.char( string.byte( contents, i ) )

        if char ~= "|" then
            str = str..char
        else
            scores[n] = tonumber( str )
            n = n + 1
            str = ""
        end
    end

    return scores[1]
end

有任何想法吗?

4

2 回答 2

0

我没有看到您实际上试图将任何内容与 Highscore 连接的任何地方。我也看不到你在哪里初始化它。默认情况下,未初始化的变量为零。如果您尝试在某处打印 Highscore,例如:

 print("Highscore: " .. Highscore)

你会得到那个错误。如果你没有那个错误,你可能会在尝试将数字与 nil 进行比较时遇到另一个错误。因此,请确保在某处初始化 Highscore,它应该可以解决您的问题。

于 2013-10-14T01:13:16.730 回答
0

在您的 MAIN.LUA 中使用此代码

-- Read and Write Settings 
-----------------------------------------------------------------------------------
local path = system.pathForFile( "myGameSettings.json", system.DocumentsDirectory )
-- io.open opens a file at path. returns nil if no file found
local createNewMGS, errStr = io.open( path, "r" )

if createNewMGS then
   --do nothing 
else
   -- create file because it doesn't exist yet
   createNewMGS = io.open( path, "w" )
   if createNewMGS then
        print( "Created new myGameSettings" )
        local loadsave = require("loadsave")
        ----------------------------------
        myGameSettings = {}
        myGameSettings.HighScore = 0
        -- here you can create settings

        ---------------------------------
        loadsave.saveTable(myGameSettings, "myGameSettings.json")
   else
        print( "Create file failed!" )
   end
end
io.close( createNewMGS )

local loadsave = require("loadsave")
--------------------------------
myGameSettings = {}
myGameSettings.HighScore = 0
-- here you can create settings

-------------------------------
--read sittings
myGameSettings = loadsave.loadTable("myGameSettings.json")
于 2013-11-07T03:03:03.793 回答