lua - 用于 conky 的 Lua 脚本运行没有错误,但不绘制任何东西
问题描述
我是 lua 新手,并试图通过为conky创建脚本来深入了解它。在我的示例中,我试图将 cairo 功能封装到Canvas 对象和可添加到画布中的可绘制对象(即 Text 对象)中。
当我尝试将cairo_surface和cairo对象存储在表中时,我无法再使用它们了。即使没有发生错误(没有消息或段错误或泄漏),第二个示例中也没有显示任何文本。
这个例子有效:
Canvas = {
init = function (w)
local cs = cairo_xlib_surface_create(w.display,w.drawable,w.visual,w.width,w.height)
local cr = cairo_create(cs)
return cr, cs
end,
destroy = function (cr, cs)
cairo_destroy(cr)
cairo_surface_destroy(cs)
end
}
function conky_main ()
if conky_window == nil then
return
else
local cr, cs = Canvas.init(conky_window)
local tx = Text:new{text="Hello World!"}
tx:draw(cr)
Canvas.destroy(cr, cs)
end
end
此示例不起作用:
Canvas = {
init = function (w) -- returns table instead of 2 variables
return {
cs = cairo_xlib_surface_create(w.display,w.drawable,w.visual,w.width,w.height),
cr = cairo_create(cs)
}
end,
destroy = function (cnv)
cairo_destroy(cnv.cr)
cairo_surface_destroy(cnv.cs)
end
}
function conky_main ()
if conky_window == nil then
return
else
local cnv = Canvas.init(conky_window)
local tx = Text:new{text="Hello World!"}
tx:draw(cnv.cr) -- access table member instead of variable
Canvas.destroy(cnv)
end
end
解决方案
return {
cs = cairo_xlib_surface_create(w.display,w.drawable,w.visual,w.width,w.height),
cr = cairo_create(cs)
}
在 Lua 表构造函数中,无法访问正在构造的表的其他字段。
cs
in 表达式cr = cairo_create(cs)
是指(全局)变量cs
而不是表字段cs
。
解决方法:引入局部变量cs
并在创建表之前对其进行初始化。
local cs = cairo_xlib_surface_create(w.display,w.drawable,w.visual,w.width,w.height)
return { cs = cs, cr = cairo_create(cs) }
推荐阅读
- r - 如何在一个组中应用一个函数,该函数取决于该组中的哪一行保存一个值?
- stripe-payments - 更新 Stripe Price 对象
- html - 如何用导航栏下的侧边栏填充剩余的视口高度?
- javascript - 为什么 css 不适用于锚标签?
- sql-server - 如果使用 docker,SQL Server 中的数据库容量是无限的吗?
- javascript - 无法在“节点”上执行“插入前”:参数 1 在 Javascript 上不是“节点”类型
- javascript - 在 Javascript 中创建一个固定长度的队列数组
- bash - 使用 shell 可执行文件动态更改 Lambda 层的版本号
- javascript - 如何让 Web 服务器在一段时间后或关闭选项卡时删除系统上的文件
- kml - 为什么这个 .kml 文件在零纬度/零经度加载?