src/luaevent.c

changeset 22
48a109847dce
parent 20
71bc2e49366c
child 23
897150985f13
equal deleted inserted replaced
21:728aafac9682 22:48a109847dce
8 #include <lauxlib.h> 8 #include <lauxlib.h>
9 #include <assert.h> 9 #include <assert.h>
10 10
11 #define EVENT_BASE_MT "EVENT_BASE_MT" 11 #define EVENT_BASE_MT "EVENT_BASE_MT"
12 12
13 le_base* event_base_get(lua_State* L, int idx) {
14 return (le_base*)luaL_checkudata(L, idx, EVENT_BASE_MT);
15 }
16
13 int luaevent_newbase(lua_State* L) { 17 int luaevent_newbase(lua_State* L) {
14 le_base *base = (le_base*)lua_newuserdata(L, sizeof(le_base)); 18 le_base *base = (le_base*)lua_newuserdata(L, sizeof(le_base));
15 base->loop_L = NULL; /* No running loop */ 19 base->loop_L = NULL; /* No running loop */
16 base->base = event_init(); 20 base->base = event_init();
17 luaL_getmetatable(L, EVENT_BASE_MT); 21 luaL_getmetatable(L, EVENT_BASE_MT);
18 lua_setmetatable(L, -2); 22 lua_setmetatable(L, -2);
19 return 1; 23 return 1;
20 } 24 }
21 25
22 static int luaevent_base_gc(lua_State* L) { 26 static int luaevent_base_gc(lua_State* L) {
23 le_base *base = luaL_checkudata(L, 1, EVENT_BASE_MT); 27 le_base *base = event_base_get(L, 1);
24 if(base->base) { 28 if(base->base) {
25 event_base_free(base->base); 29 event_base_free(base->base);
26 base->base = NULL; 30 base->base = NULL;
27 } 31 }
28 return 0; 32 return 0;
41 return fd; 45 return fd;
42 } 46 }
43 47
44 /* sock, event, callback */ 48 /* sock, event, callback */
45 static int luaevent_addevent(lua_State* L) { 49 static int luaevent_addevent(lua_State* L) {
46 int fd, event, callbackRef; 50 int fd, event;
47 le_callback* arg; 51 le_callback* arg = event_callback_push(L, 1, 4);
48 le_base *base = luaL_checkudata(L, 1, EVENT_BASE_MT);
49 fd = getSocketFd(L, 2); 52 fd = getSocketFd(L, 2);
50 event = luaL_checkinteger(L, 3); 53 event = luaL_checkinteger(L, 3);
51 luaL_checktype(L, 4, LUA_TFUNCTION);
52 lua_pushvalue(L, 4);
53 callbackRef = luaL_ref(L, LUA_REGISTRYINDEX);
54 arg = lua_newuserdata(L, sizeof(*arg));
55 luaL_getmetatable(L, EVENT_CALLBACK_ARG_MT);
56 lua_setmetatable(L, -2);
57
58 arg->base = base;
59 arg->callbackRef = callbackRef;
60 /* Setup event... */ 54 /* Setup event... */
61 event_set(&arg->ev, fd, event | EV_PERSIST, luaevent_callback, arg); 55 event_set(&arg->ev, fd, event | EV_PERSIST, luaevent_callback, arg);
62 event_base_set(base->base, &arg->ev); 56 event_base_set(arg->base->base, &arg->ev);
63 event_add(&arg->ev, NULL); 57 event_add(&arg->ev, NULL);
64 return 1; 58 return 1;
65 } 59 }
66 60
67 static int luaevent_loop(lua_State* L) { 61 static int luaevent_loop(lua_State* L) {
68 le_base *base = luaL_checkudata(L, 1, EVENT_BASE_MT); 62 le_base *base = event_base_get(L, 1);
69 base->loop_L = L; 63 base->loop_L = L;
70 int ret = event_base_loop(base->base, 0); 64 int ret = event_base_loop(base->base, 0);
71 lua_pushinteger(L, ret); 65 lua_pushinteger(L, ret);
72 return 1; 66 return 1;
73 } 67 }

mercurial