lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 7/9/2012 1:34 AM, Laurent FAILLIE wrote:
Hello,

Continuing to explore LGI possibilities, I'm facing issues when I'm
trying to use timeout_add_seconds().

When using lgi to call GLib-based APIs, do not use (simply skip) all GDestroyNotify and user_data-style arguments, they are provided internally by lgi. So this would mean that the call of

guint g_timeout_add_seconds (guint interval, GSourceFunc function, gpointer data);

in lgi should be something like:

local id = GLib.timeout_add_seconds (interval, function() ... end)

Unfortunately, this case got somehow complicated by someone adding rename-to annotation to GLib which renames timeout_add_seconds_full() to timeout_add_seconds(), so when you call timeout_add_seconds, you are actually calling timeout_add_seconds_full(), with following prototype:

guint g_timeout_add_seconds_full (gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify);

so the correct lgi call looks something like this:

local id = GLib.timeout_add_seconds (GLib.PRIORITY_DEFAULT, interval, function() ... end)

Tip: when you are not sure about how the prototype for Lua-side call should look like, look up the requested function in the .gir file, i.e. in this case /usr/share/gir-1.0/GLib-2.0.gir. It is basically XML-version of .typelib files used by lgi to marshal the calls.

Moreover, your original code would not work. All timeout_add and idle_add functions work only when mainloop is running. Moreover, you need to 'return true' from callback handlers if you want them to be invoked again. Following code does approximately what you were probably trying to achieve:

local lgi = require 'lgi'
local GLib = lgi.GLib

local main_loop = GLib.MainLoop()

cnt = 0

function tictac()
    cnt = cnt + 1
    print("tic")
    return true
end

GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, tictac)
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1,
			 function()
			    print( cnt )
			    return true
			 end)

main_loop:run()

HTH,
pavel