Apply http://prosody.im/patches/luaevent-catch-errors-1.patch
[luaevent.git] / src / utility.c
blob9f630ece42d325e4b479060c92d82861f8493811
1 /* LuaEvent - Copyright (C) 2007,2012 Thomas Harning <harningt@gmail.com>
2 * Licensed as LGPL - See doc/COPYING for details */
3 #include "utility.h"
4 #include <lauxlib.h>
6 #define WEAK_REF_LOCATION le_register_utility
8 static void get_weakref_table(lua_State* L) {
9 lua_pushlightuserdata(L, WEAK_REF_LOCATION);
10 lua_gettable(L, LUA_REGISTRYINDEX);
13 void le_weak_ref(lua_State* L, void* ptr, int idx) {
14 get_weakref_table(L);
15 lua_pushlightuserdata(L, ptr);
16 if(idx < 0) idx-=2;
17 lua_pushvalue(L, idx);
18 lua_settable(L, -3);
20 void le_weak_unref(lua_State* L, void* ptr) {
21 get_weakref_table(L);
22 lua_pushlightuserdata(L, ptr);
23 lua_pushnil(L);
24 lua_settable(L, -3);
27 void le_weak_get(lua_State* L, void* ptr) {
28 get_weakref_table(L);
29 lua_pushlightuserdata(L, ptr);
30 lua_gettable(L, -2);
33 static void push_weak_table(lua_State* L, const char* mode) {
34 lua_newtable(L);
35 lua_createtable(L,0,1);
36 lua_pushstring(L,mode);
37 lua_setfield(L,-2,"__mode");
38 lua_setmetatable(L,-2);
41 void le_register_utility(lua_State* L) {
42 lua_pushlightuserdata(L, WEAK_REF_LOCATION);
43 push_weak_table(L, "v");
44 lua_settable(L, LUA_REGISTRYINDEX);