Corona的HighScore。文件读/写

时间:2013-10-08 16:25:05

标签: android file lua corona

我有这个错误:

  

尝试连接全局'Highscore'(nil值)

这是我在Game.lua文件中检查Highscore的方法:

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

这是我在score.txt中保存Highscore的方法,我在所有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

任何想法?

2 个答案:

答案 0 :(得分:0)

我没有看到任何你正在尝试用Highscore连接任何东西的地方。我也不知道你在哪里初始化它。默认情况下,未初始化的变量为零。如果你想在某个地方打印出Highscore:

 print("Highscore: " .. Highscore)

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

答案 1 :(得分: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")