3

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?

Michael
  • 876
  • 9
  • 29
  • I guess you need to do `local extents={}` or `extents = cairo_text_extents(cr, utf8)`. – lhf Mar 08 '17 at 12:51
  • I do not think so, since the function `cairo_text_extents` does not return anything, in fact in `C` you are expected to pass it `&extents`, where `&extents` being the memory address of a variable of type `cairo_text_extents_t`. – Michael Mar 08 '17 at 12:54

1 Answers1

6

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 new cairo_text_extents_t structure. A creation function for this structure is not provided by the cairo API. After calling this, you should use tolua.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)
Michael
  • 876
  • 9
  • 29