I am writing some widget in lua to be used by conky
to display some stuff.
I reached a point in which I would like to center text. Following this tutorial, I ported the C
code into lua
code, so it now looks like this:
local extents
local utf8 = "cairo"
local x, y
cairo_select_font_face(cr, "Ubuntu", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL)
cairo_set_font_size(cr, 13)
cairo_text_extents(cr, utf8, extents)
x = 128.0 - (extents.width / 2 + extents.x_bearing)
y = 128.0 - (extents.height / 2 + extents.y_bearing)
cairo_move_to(cr, x, y)
cairo_show_text(cr, utf8)
The problem I am dealing with now is that the C
data type cairo_text_extents_t
that should be passed to the cairo_text_extents
is not recognized by lua
, in fact conky
closes without any output.
Is there a way to make lua
recognize that data type?
I finally found the answer. In conky there exists a function that does what I need, as specified here:
cairo_text_extents_t:create() function
Call this function to return a newcairo_text_extents_t
structure. A creation function for this structure is not provided by the cairo API. After calling this, you should usetolua.takeownership()
on the return value to ensure ownership is passed properly.
So, it is sufficient to do the following:
local extents = cairo_text_extents_t:create()
tolua.takeownership(extents)
local utf8 = "cairo"
local x, y
cairo_select_font_face(cr, "Ubuntu", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL)
cairo_set_font_size(cr, 52)
cairo_text_extents(cr, utf8, extents)
x = 128.0 - (extents.width / 2 + extents.x_bearing)
y = 128.0 - (extents.height / 2 + extents.y_bearing)
cairo_move_to (cr, x, y)
cairo_show_text (cr, utf8)