glib_timeout.c
author Myhailo Danylenko <isbear@ukrpost.net>
Mon, 09 Feb 2009 13:00:42 +0200
changeset 2 34b6fedde9eb
parent 0 84fdfb0344c9
permissions -rw-r--r--
Switch to cmake


#include <lua.h>
#include <lauxlib.h>
#include <glib.h>

#include "util.h"
#include "glib_types.h"

/// timeout callback function
/// Function, that will be called periodically until it returns false.
/// R: boolean
static gboolean lglib_timeout_callback (lglib_callback_t *cb)
{
	lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
	if (lua_pcall (cb->L, 0, 1, 0)) {
		// XXX lua_error (cb->L);
		lua_pop (cb->L, 1);
		return FALSE;
	}
	return lua_toboolean (cb->L, -1);
}

/// g.timeout.new
/// Creates new timeout in default context.
/// A: integer (priority), integer (interval, seconds), timeout callback function
/// R: integer (id of the event source)
static int lglib_timeout_new (lua_State *L)
{
	int priority = luaL_checkint (L, 1);
	int interval = luaL_checkint (L, 2);
	lglib_callback_t *cb;
	luaL_argcheck (L, lua_isfunction (L, 3), 3, "function expected");

	cb = luaL_malloc (L, sizeof (lglib_callback_t));
	cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
	cb->L         = L;

	lua_pushnumber (L, g_timeout_add_seconds_full (priority, interval,
						       (GSourceFunc)lglib_timeout_callback,
						       cb,
						       (GDestroyNotify)lglib_callback_destroy));
	return 1;
}

/// g.timeout.source
/// Creates new timeout source.
/// A: interval
/// R: g source object
static int lglib_timeout_source (lua_State *L)
{
	int interval = luaL_checkint (L, 1);
	GSource *source = g_timeout_source_new_seconds (interval);
	lglib_source_bless (L, source);
	// XXX s_source_unref (source);
	return 1;
}

static const luaL_Reg lglib_timeout_reg_f[] = {
	{ "new",    lglib_timeout_new    },
	{ "source", lglib_timeout_source },
	{ NULL,     NULL                 },
};

int luaopen_glib_timeout (lua_State *L)
{
	luaL_register (L, "g.timeout", lglib_timeout_reg_f);
	return 1;
}