简体   繁体   中英

Simple highscore using preferences (Lua - Corona SDK)

And thanks in advance for your help!

I'm trying to implement in my game an highscore feature using "preferences" in Lua, but i'm missing something, here's my code:

local highscore_letta = system.getPreference( "app", "highscore", "number" )

-- if preference do not exist, create it and set it to 0 (first time playing the game)
if (highscore_letta == nil) then
    local appPreferences =
    {
        highscore = "0"
    }
    system.setPreferences( "app", appPreferences )
end

-- if the score is higher than current highscore, update it with the new one
if (_G.player_score > highscore_letta) then
    local appPreferences =
    {
        highscore = _G.player_score
    }
    system.setPreferences( "app", appPreferences )
end

After the player lose for the first time, the game crashes saying that it's comparing a null value in "highscore_letta". After a second try, the game do not crashes, but it sticks with 0 and never update it at all.

Any advice? I can't figure out what i'm missing. Thanks again!

Try

local highscore_letta = system.getPreference( "app", "highscore", "number" ) or 0

-- if the score is higher than current highscore, update it with the new one
if (_G.player_score > highscore_letta) then
    local appPreferences =
    {
        highscore = _G.player_score
    }
    system.setPreferences( "app", appPreferences )
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM