在corona中使用getPreference和setPreferences遇到问题

迄今为止,我一直在遵循corona网站上的教程,一切都进行得很顺利。

但是在教程“显示和保存分数”中,我似乎遇到了以下运行时错误。

尝试调用字段setPreferences'(一个空值)

这是score.lua的代码

local M = {}

M.score = 0

function M.init( options )

    local customOptions = options or {}   -- 好用的"或"运算符
    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   -- 使得分数位于顶部,其字体大小的一半。
    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"   -- 使其在其他模块中可访问。

    -- 创建分数显示对象
    M.scoreText = display.newText( string.format( M.format, 0 ), opt.x, opt.y, opt.font, opt.fontSize )   -- string.format() 像printf和scanf语句一样工作
    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 ("当前分数为" .. M.score)
    local saved = system.setPreferences( "app", { currentScore=M.score } )
    if ( saved == false) then
        print ( "错误:无法保存分数" )
    end
end

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

    if  ( score ) then
        return tonumber(score)
    else
        print( "错误:无法加载分数(分数可能不存在在存储中)" )
    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 ) -- 将分数设置为value
score.save()

我知道还有其他方法可以保留分数,但我想知道我的代码中的问题是什么。我到处搜索,但找不到任何解决方案。也尝试在我的智能手机上构建,但最终出现了相同的错误。

点赞
用户5525442
用户5525442

从 Corona 文档中

语法

system.setPreferences( category, preferences )

category(必需) 字符串。表示哪个偏好设置应该在系统上访问。目前,只支持“app”类别 - 这是 Corona 应用程序开发人员定义的应用程序自定义偏好设置。

preferences(必需) 表。要写入存储的偏好设置表。此表应包含键值对,其中键是偏好设置的唯一名称,其值为布尔值数字字符串

如果您的 M.score 为空,则可能会出现错误 请尝试这个

local saved = system.setPreferences( "app", { currentScore=M.score or 0 } )
2018-10-17 11:34:40