Added missing license header
[luaevent.git] / src / event_callback.c
blob0d320ebee03b440834ba612babaa8d75049f208f
1 /* LuaEvent - Copyright (C) 2007 Thomas Harning <harningt@gmail.com>
2 * Licensed as LGPL - See doc/COPYING for details */
3 #include "event_callback.h"
4 #include <assert.h>
5 #include <lauxlib.h>
7 void freeCallbackArgs(le_callback* arg, lua_State* L) {
8 if(arg->base) {
9 arg->base = NULL;
10 event_del(&arg->ev);
11 luaL_unref(L, LUA_REGISTRYINDEX, arg->callbackRef);
14 /* le_callback is allocated at the beginning of the coroutine in which it
15 is used, no need to manually de-allocate */
17 /* Index for coroutine is fd as integer for *nix, as lightuserdata for Win */
18 void luaevent_callback(int fd, short event, void* p) {
19 le_callback* arg = p;
20 lua_State* L;
21 int ret;
22 assert(arg && arg->base && arg->base->loop_L);
23 L = arg->base->loop_L;
24 lua_rawgeti(L, LUA_REGISTRYINDEX, arg->callbackRef);
25 lua_pushinteger(L, event);
26 lua_call(L, 1, 1);
27 ret = lua_tointeger(L, -1);
28 lua_pop(L, 1);
29 if(ret == -1) {
30 freeCallbackArgs(arg, L);
31 } else {
32 struct event *ev = &arg->ev;
33 int newEvent = ret;
34 if(newEvent != event) { // Need to hook up new event...
35 event_del(ev);
36 event_set(ev, fd, EV_PERSIST | newEvent, luaevent_callback, arg);
37 event_add(ev, NULL);
42 static int luaevent_cb_gc(lua_State* L) {
43 le_callback* arg = luaL_checkudata(L, 1, EVENT_CALLBACK_ARG_MT);
44 freeCallbackArgs(arg, L);
45 return 0;
48 int event_callback_register(lua_State* L) {
49 luaL_newmetatable(L, EVENT_CALLBACK_ARG_MT);
50 lua_pushcfunction(L, luaevent_cb_gc);
51 lua_setfield(L, -2, "__gc");
52 lua_newtable(L);
53 lua_pushcfunction(L, luaevent_cb_gc);
54 lua_setfield(L, -2, "close");
55 lua_setfield(L, -2, "__index");
56 lua_pop(L, 1);
57 return 0;