+static void ul_ufd_cb(struct uloop_fd *fd, unsigned int events)
+{
+ struct lua_uloop_fd *ufd = container_of(fd, struct lua_uloop_fd, fd);
+
+ lua_getglobal(state, "__uloop_cb");
+ lua_rawgeti(state, -1, ufd->r);
+ lua_remove(state, -2);
+
+ /* push fd object */
+ lua_getglobal(state, "__uloop_fds");
+ lua_rawgeti(state, -1, ufd->fd_r);
+ lua_remove(state, -2);
+
+ /* push events */
+ lua_pushinteger(state, events);
+ lua_call(state, 2, 0);
+}
+
+
+static int get_sock_fd(lua_State* L, int idx) {
+ int fd;
+ if(lua_isnumber(L, idx)) {
+ fd = lua_tonumber(L, idx);
+ } else {
+ luaL_checktype(L, idx, LUA_TUSERDATA);
+ lua_getfield(L, idx, "getfd");
+ if(lua_isnil(L, -1))
+ return luaL_error(L, "socket type missing 'getfd' method");
+ lua_pushvalue(L, idx - 1);
+ lua_call(L, 1, 1);
+ fd = lua_tointeger(L, -1);
+ lua_pop(L, 1);
+ }
+ return fd;
+}
+
+static int ul_ufd_delete(lua_State *L)
+{
+ struct lua_uloop_fd *ufd = lua_touserdata(L, 1);
+
+ uloop_fd_delete(&ufd->fd);
+
+ /* obj.__index.__gc = nil , make sure executing only once*/
+ lua_getfield(L, -1, "__index");
+ lua_pushstring(L, "__gc");
+ lua_pushnil(L);
+ lua_settable(L, -3);
+
+ lua_getglobal(state, "__uloop_cb");
+ luaL_unref(state, -1, ufd->r);
+ lua_remove(state, -1);
+
+ lua_getglobal(state, "__uloop_fds");
+ luaL_unref(state, -1, ufd->fd_r);
+ lua_remove(state, -1);
+
+ return 1;
+}
+
+static const luaL_Reg ufd_m[] = {
+ { "delete", ul_ufd_delete },
+ { NULL, NULL }
+};
+
+static int ul_ufd_add(lua_State *L)
+{
+ struct lua_uloop_fd *ufd;
+ int fd = 0;
+ unsigned int flags = 0;
+ int ref;
+ int fd_ref;
+
+ if (lua_isnumber(L, -1)) {
+ flags = lua_tointeger(L, -1);
+ lua_pop(L, 1);
+ }
+
+ if (!lua_isfunction(L, -1)) {
+ lua_pushstring(L, "invalid arg list");
+ lua_error(L);
+
+ return 0;
+ }
+
+ fd = get_sock_fd(L, -2);
+
+ lua_getglobal(L, "__uloop_cb");
+ lua_pushvalue(L, -2);
+ ref = luaL_ref(L, -2);
+ lua_pop(L, 1);
+
+ lua_getglobal(L, "__uloop_fds");
+ lua_pushvalue(L, -3);
+ fd_ref = luaL_ref(L, -2);
+ lua_pop(L, 1);
+
+ ufd = ul_create_userdata(L, sizeof(*ufd), ufd_m, ul_ufd_delete);
+ ufd->r = ref;
+ ufd->fd.fd = fd;
+ ufd->fd_r = fd_ref;
+ ufd->fd.cb = ul_ufd_cb;
+ if (flags)
+ uloop_fd_add(&ufd->fd, flags);
+
+ return 1;
+}
+
+static int ul_process_free(lua_State *L)
+{
+ struct lua_uloop_process *proc = lua_touserdata(L, 1);
+
+ /* obj.__index.__gc = nil , make sure executing only once*/
+ lua_getfield(L, -1, "__index");
+ lua_pushstring(L, "__gc");
+ lua_pushnil(L);
+ lua_settable(L, -3);
+
+ if (proc->r != LUA_NOREF) {
+ uloop_process_delete(&proc->p);
+
+ lua_getglobal(state, "__uloop_cb");
+ luaL_unref(state, -1, proc->r);
+ lua_remove(state, -1);
+ }
+
+ return 1;
+}
+
+static const luaL_Reg process_m[] = {
+ { "delete", ul_process_free },
+ { NULL, NULL }
+};
+