在corona中使用getPreference和setPreferences遇到问题
2018-10-17 4:56:53
收藏:0
阅读:148
评论:1
迄今为止,我一直在遵循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()
我知道还有其他方法可以保留分数,但我想知道我的代码中的问题是什么。我到处搜索,但找不到任何解决方案。也尝试在我的智能手机上构建,但最终出现了相同的错误。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

从 Corona 文档中
category(必需) 字符串。表示哪个偏好设置应该在系统上访问。目前,只支持“app”类别 - 这是 Corona 应用程序开发人员定义的应用程序自定义偏好设置。
preferences(必需) 表。要写入存储的偏好设置表。此表应包含键值对,其中键是偏好设置的唯一名称,其值为布尔值、数字或字符串。
如果您的
M.score为空,则可能会出现错误 请尝试这个local saved = system.setPreferences( "app", { currentScore=M.score or 0 } )