lua/uloop: 'end' is the keyword of Lua, use 'cancel' replace it.
[project/libubox.git] / lua / uloop.c
index c71d537a5a904f83028caad2818cbeb0cbbcfe4b..2a0a516b5e2be149d6713d5a304ae5a14709a73c 100644 (file)
@@ -77,10 +77,17 @@ static int ul_timer_set(lua_State *L)
 static int ul_timer_free(lua_State *L)
 {
        struct lua_uloop_timeout *tout = lua_touserdata(L, 1);
-
+       
        uloop_timeout_cancel(&tout->t);
+       
+       /* 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(L, -1, tout->r);
+       luaL_unref(state, -1, tout->r);
 
        return 1;
 }
@@ -150,7 +157,6 @@ static void ul_ufd_cb(struct uloop_fd *fd, unsigned int events)
 
        /* push events */
        lua_pushinteger(state, events);
-
        lua_call(state, 2, 0);
 }
 
@@ -172,6 +178,34 @@ static int get_sock_fd(lua_State* L, int idx) {
        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;
@@ -205,6 +239,18 @@ static int ul_ufd_add(lua_State *L)
        lua_pop(L, 1);
 
        ufd = lua_newuserdata(L, sizeof(*ufd));
+
+       lua_createtable(L, 0, 2);
+       lua_pushvalue(L, -1);
+       lua_setfield(L, -2, "__index");
+       lua_pushcfunction(L, ul_ufd_delete);
+       lua_setfield(L, -2, "__gc");
+       lua_pushvalue(L, -1);
+       lua_setmetatable(L, -3);
+       lua_pushvalue(L, -2);
+       luaI_openlib(L, NULL, ufd_m, 1);
+       lua_pushvalue(L, -2);
+
        memset(ufd, 0, sizeof(*ufd));
 
        ufd->r = ref;
@@ -311,12 +357,19 @@ static int ul_run(lua_State *L)
        return 1;
 }
 
+static int ul_end(lua_State *L)
+{
+       uloop_end();
+       return 1;
+}
+
 static luaL_reg uloop_func[] = {
        {"init", ul_init},
        {"run", ul_run},
        {"timer", ul_timer},
        {"process", ul_process},
        {"fd_add", ul_ufd_add},
+       {"cancel", ul_end},
        {NULL, NULL},
 };