glib_timeout.c
changeset 0 84fdfb0344c9
equal deleted inserted replaced
-1:000000000000 0:84fdfb0344c9
       
     1 
       
     2 #include <lua.h>
       
     3 #include <lauxlib.h>
       
     4 #include <glib.h>
       
     5 
       
     6 #include "util.h"
       
     7 #include "glib_types.h"
       
     8 
       
     9 /// timeout callback function
       
    10 /// Function, that will be called periodically until it returns false.
       
    11 /// R: boolean
       
    12 static gboolean lglib_timeout_callback (lglib_callback_t *cb)
       
    13 {
       
    14 	lua_rawgeti (cb->L, LUA_REGISTRYINDEX, cb->reference);
       
    15 	if (lua_pcall (cb->L, 0, 1, 0)) {
       
    16 		// XXX lua_error (cb->L);
       
    17 		lua_pop (cb->L, 1);
       
    18 		return FALSE;
       
    19 	}
       
    20 	return lua_toboolean (cb->L, -1);
       
    21 }
       
    22 
       
    23 /// g.timeout.new
       
    24 /// Creates new timeout in default context.
       
    25 /// A: integer (priority), integer (interval, seconds), timeout callback function
       
    26 /// R: integer (id of the event source)
       
    27 static int lglib_timeout_new (lua_State *L)
       
    28 {
       
    29 	int priority = luaL_checkint (L, 1);
       
    30 	int interval = luaL_checkint (L, 2);
       
    31 	lglib_callback_t *cb;
       
    32 	luaL_argcheck (L, lua_isfunction (L, 3), 3, "function expected");
       
    33 
       
    34 	cb = luaL_malloc (L, sizeof (lglib_callback_t));
       
    35 	cb->reference = luaL_ref (L, LUA_REGISTRYINDEX);
       
    36 	cb->L         = L;
       
    37 
       
    38 	lua_pushnumber (L, g_timeout_add_seconds_full (priority, interval,
       
    39 						       (GSourceFunc)lglib_timeout_callback,
       
    40 						       cb,
       
    41 						       (GDestroyNotify)lglib_callback_destroy));
       
    42 	return 1;
       
    43 }
       
    44 
       
    45 /// g.timeout.source
       
    46 /// Creates new timeout source.
       
    47 /// A: interval
       
    48 /// R: g source object
       
    49 static int lglib_timeout_source (lua_State *L)
       
    50 {
       
    51 	int interval = luaL_checkint (L, 1);
       
    52 	GSource *source = g_timeout_source_new_seconds (interval);
       
    53 	lglib_source_bless (L, source);
       
    54 	// XXX s_source_unref (source);
       
    55 	return 1;
       
    56 }
       
    57 
       
    58 static const luaL_Reg lglib_timeout_reg_f[] = {
       
    59 	{ "new",    lglib_timeout_new    },
       
    60 	{ "source", lglib_timeout_source },
       
    61 	{ NULL,     NULL                 },
       
    62 };
       
    63 
       
    64 int luaopen_glib_timeout (lua_State *L)
       
    65 {
       
    66 	luaL_register (L, "g.timeout", lglib_timeout_reg_f);
       
    67 	return 1;
       
    68 }
       
    69