电晕中的 getPreference 和 setPreferences 有问题

Having problem with getPreference and setPreferences in corona

我一直在关注 corona 网站上的教程,到目前为止一切顺利。

但是在教程中 "Displaying and saving score" 我似乎有以下运行时错误。

attempt to call field setPreferences' (a nil value)

这是score.lua

的代码
local M = {}

M.score = 0

function M.init( options )

    local customOptions = options or {}   -- nice use of "or" operator
    local opt = {}
    opt.fontSize = customOptions.fontSize or 24
    opt.font = customOptions.font or native.systemFont
    opt.x = customOptions.x or display.contentCenterX
    opt.y = customOptions.y or opt.fontSize*0.5   -- such that the score is positioned at the top, half of its font size.
    opt.maxDigits = customOptions.maxDigits or 6
    opt.leadingZeros = customOptions.leadingZeros or false

    local prefix = ""
    if ( opt.leadingZeros ) then
        prefix = "0"
    end
    M.format = "%" .. prefix .. opt.maxDigits .. "d"   -- so that its accesible in other modules.

    -- Create the score display object 
    M.scoreText = display.newText( string.format( M.format, 0 ), opt.x, opt.y, opt.font, opt.fontSize )   -- string.format() works like printf and scanf statements
    M.scoreText:setFillColor(1,0,0)
    return M.scoreText
end

function M.set( value )

    M.score = tonumber(value)
    M.scoreText.text = string.format( M.format, M.score )

end

function M.get()

    return M.score
end

function M.add( amount ) 

    M.score = M.score + tonumber(amount)
    M.scoreText.text = string.format( M.format, M.score )
end

function M.save()
    print (" the score is " .. M.score)
    local saved = system.setPreferences( "app", { currentScore=M.score } )
    if ( saved == false) then
        print ( "ERROR: could not save score" )
    end
end

function M.load()
    local score = system.getPreference( "app", "currentScore", "number" ) 

    if  ( score ) then
        return tonumber(score)
    else
        print( "ERROR: could not load score (score may not exist in storage)" )
    end
end

return M

这是main.lua

的代码
local score = require( "score" )

local scoreText = score.init(
{
    fontSize = 20,
    font = "CoolCustomFont.ttf",
    x = display.contentCenterX,
    y = 30,
    maxDigits = 7,
    leadingZeros = true
})

local savedScore = score.load()
score.set( 1000 ) -- Sets the score to value
score.save()

我知道还有其他保持分数的方法,但我想知道我的代码中存在什么问题。我到处搜索,但找不到任何解决方案。也许我在某个地方犯了一个我无法识别的错误。

甚至尝试在我的 smart phone 上构建,但最终得到了同样的错误。

来自 corona 文档

Syntax

system.setPreferences( category, preferences )

类别(必填) 细绳。指示应在系统上访问哪一组首选项。目前,仅支持 "app" 类别——这是由 Corona 应用程序开发人员定义的应用程序自定义首选项。

首选项(必需) Table。 Table 个要写入存储的首选项。此 table 应包含键值对,其中键是首选项的唯一名称,其值是 booleannumber, 或 字符串.

如果你的 M.score 是 nil 那么你可能会得到一个错误 试试这个

local saved = system.setPreferences( "app", { currentScore=M.score or 0 } )