/* LUA: new(fd, read, write, error) Pushes a new bufferevent instance on the stack Accepts: base, fd, read, write, error cb Requires base, fd and error cb */ static int buffer_event_push(lua_State* L) { le_bufferevent *ev; le_base* base = event_base_get(L, 1); /* NOTE: Should probably reference the socket as well... */ int fd = getSocketFd(L, 2); luaL_checktype(L, 5, LUA_TFUNCTION); if(!lua_isnil(L, 3)) luaL_checktype(L, 3, LUA_TFUNCTION); if(!lua_isnil(L, 4)) luaL_checktype(L, 4, LUA_TFUNCTION); ev= (le_bufferevent*)lua_newuserdata(L, sizeof(le_bufferevent)); luaL_getmetatable(L, BUFFER_EVENT_MT); lua_setmetatable(L, -2); ev->ev = bufferevent_new(fd, buffer_event_readcb, buffer_event_writecb, buffer_event_errorcb, ev); lua_createtable(L, 5, 0); lua_pushvalue(L, 3); lua_rawseti(L, -2, 1); // Read lua_pushvalue(L, 4); lua_rawseti(L, -2, 2); // Write lua_pushvalue(L, 5); lua_rawseti(L, -2, 3); // Err event_buffer_push(L, ev->ev->input); lua_rawseti(L, -2, READ_BUFFER_LOCATION); event_buffer_push(L, ev->ev->output); lua_rawseti(L, -2, WRITE_BUFFER_LOCATION); lua_setfenv(L, -2); ev->base = base; return 1; }
static int luaevent_base_gc(lua_State* L) { le_base *base = event_base_get(L, 1); if(base->base) { event_base_free(base->base); base->base = NULL; } return 0; }
static int luaevent_method(lua_State* L) { #ifdef _EVENT_VERSION le_base *base = event_base_get(L, 1); if(strcmp(_EVENT_VERSION, "1.3")<0) lua_pushstring(L, event_base_get_method(base->base)); else #endif lua_pushstring(L, event_base_get_method(base->base)); return 1; }
static int luaevent_loopexit(lua_State*L) { int ret; le_base *base = event_base_get(L, 1); struct timeval tv = { 0, 0 }; if(lua_gettop(L) >= 2) /* Optional timeout before exiting the loop */ load_timeval(luaL_checknumber(L, 2), &tv); ret = event_base_loopexit(base->base, &tv); lua_pushinteger(L, ret); return 1; }
le_callback* event_callback_push(lua_State* L, int baseIdx, int callbackIdx) { le_callback* cb; le_base *base = event_base_get(L, baseIdx); luaL_checktype(L, callbackIdx, LUA_TFUNCTION); cb = lua_newuserdata(L, sizeof(*cb)); luaL_getmetatable(L, EVENT_CALLBACK_ARG_MT); lua_setmetatable(L, -2); lua_pushvalue(L, callbackIdx); cb->callbackRef = luaL_ref(L, LUA_REGISTRYINDEX); cb->base = base; memset(&cb->timeout, 0, sizeof(cb->timeout)); return cb; }
static int luaevent_loop(lua_State* L) { int ret; le_base *base = event_base_get(L, 1); base->loop_L = L; base->errorMessage = LUA_NOREF; ret = event_base_loop(base->base, 0); if(base->errorMessage != LUA_NOREF) { lua_rawgeti(L, LUA_REGISTRYINDEX, base->errorMessage); luaL_unref(L, LUA_REGISTRYINDEX, base->errorMessage); base->errorMessage = LUA_NOREF; return lua_error(L); } lua_pushinteger(L, ret); return 1; }