1 /* LuaEvent - Copyright (C) 2007 Thomas Harning <harningt@gmail.com>
2 * Licensed as LGPL - See doc/COPYING for details */
5 #include "event_callback.h"
6 #include "event_buffer.h"
12 #define EVENT_BASE_MT "EVENT_BASE_MT"
14 le_base
* event_base_get(lua_State
* L
, int idx
) {
15 return (le_base
*)luaL_checkudata(L
, idx
, EVENT_BASE_MT
);
18 int luaevent_newbase(lua_State
* L
) {
19 le_base
*base
= (le_base
*)lua_newuserdata(L
, sizeof(le_base
));
20 base
->loop_L
= NULL
; /* No running loop */
21 base
->base
= event_init();
22 luaL_getmetatable(L
, EVENT_BASE_MT
);
23 lua_setmetatable(L
, -2);
27 static int luaevent_base_gc(lua_State
* L
) {
28 le_base
*base
= event_base_get(L
, 1);
30 event_base_free(base
->base
);
36 int getSocketFd(lua_State
* L
, int idx
) {
38 luaL_checktype(L
, idx
, LUA_TUSERDATA
);
39 lua_getfield(L
, idx
, "getfd");
41 return luaL_error(L
, "Socket type missing 'getfd' method");
42 lua_pushvalue(L
, idx
);
44 fd
= lua_tointeger(L
, -1);
49 void load_timeval(double time
, struct timeval
*tv
) {
50 tv
->tv_sec
= (int)time
;
51 tv
->tv_usec
= (int)(time
* 1000000) % 1000000;
54 /* sock, event, callback, timeout */
55 static int luaevent_addevent(lua_State
* L
) {
57 le_callback
* arg
= event_callback_push(L
, 1, 4);
58 struct timeval
*tv
= &arg
->timeout
;
59 if(lua_isnil(L
, 2) && lua_isnumber(L
, 5)) {
60 fd
= -1; /* Per event_timer_set.... */
62 fd
= getSocketFd(L
, 2);
64 event
= luaL_checkinteger(L
, 3);
65 if(lua_isnumber(L
, 5)) {
66 double time
= lua_tonumber(L
, 5);
67 load_timeval(time
, tv
);
73 event_set(&arg
->ev
, fd
, event
| EV_PERSIST
, luaevent_callback
, arg
);
74 event_base_set(arg
->base
->base
, &arg
->ev
);
75 event_add(&arg
->ev
, tv
);
79 static int luaevent_loop(lua_State
* L
) {
80 le_base
*base
= event_base_get(L
, 1);
82 int ret
= event_base_loop(base
->base
, 0);
83 lua_pushinteger(L
, ret
);
87 static luaL_Reg base_funcs
[] = {
88 { "addevent", luaevent_addevent
},
89 { "loop", luaevent_loop
},
93 static luaL_Reg funcs
[] = {
94 { "new", luaevent_newbase
},
103 static namedInteger consts
[] = {
105 {"EV_READ", EV_READ
},
106 {"EV_WRITE", EV_WRITE
},
107 {"EV_TIMEOUT", EV_TIMEOUT
},
111 void setNamedIntegers(lua_State
* L
, namedInteger
* p
) {
113 lua_pushinteger(L
, p
->value
);
114 lua_setfield(L
, -2, p
->name
);
120 int luaopen_luaevent_core(lua_State
* L
) {
121 /* Register external items */
122 event_callback_register(L
);
123 event_buffer_register(L
);
124 /* Setup metatable */
125 luaL_newmetatable(L
, EVENT_BASE_MT
);
127 luaL_register(L
, NULL
, base_funcs
);
128 lua_setfield(L
, -2, "__index");
129 lua_pushcfunction(L
, luaevent_base_gc
);
130 lua_setfield(L
, -2, "__gc");
133 luaL_register(L
, "luaevent.core", funcs
);
134 setNamedIntegers(L
, consts
);