首页 > 解决方案 > 用于 conky 的 Lua 脚本运行没有错误,但不绘制任何东西

问题描述

我是 lua 新手,并试图通过为conky创建脚本来深入了解它。在我的示例中,我试图将 cairo 功能封装到Canvas 对象和可添加到画布中的可绘制对象(即 Text 对象)中。

当我尝试将cairo_surfacecairo对象存储在表中时,我无法再使用它们了。即使没有发生错误(没有消息或段错误或泄漏),第二个示例中也没有显示任何文本。

这个例子有效:

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

标签: luacairoconky

解决方案


return {
    cs = cairo_xlib_surface_create(w.display,w.drawable,w.visual,w.width,w.height),
    cr = cairo_create(cs)
}

在 Lua 表构造函数中,无法访问正在构造的表的其他字段。
csin 表达式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) }

推荐阅读