forked from hoelzro/luabdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.c
107 lines (91 loc) · 2.9 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "luabdb_private.h"
#include <lauxlib.h>
#include <lualib.h>
#include <pthread.h>
static char* g_bidiMapKey = "bidimap";
//thread local key for storing lua_State
static pthread_key_t g_luaStateKey = 0;
///bi-directional c<-->lua mapping registry (weak table)
void create_bidi_registry(lua_State *L)
{
dbgprint("create_bidi_registry %d\n", lua_gettop(L));
lua_pushlightuserdata(L, &g_bidiMapKey);
lua_newtable(L);
lua_createtable(L, 0, 1);
lua_pushstring(L, "v");
lua_setfield(L, -2, "__mode");
lua_setmetatable(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
dbgprint("create_bidi_registry end %d\n", lua_gettop(L));
}
///stores a mapping (ptrKey->lua object at index) in a mapping registry
int store_bidi_in_registry(lua_State *L, void* ptrKey, int index)
{
dbgprint("store_bidi_in_registry %d\n", lua_gettop(L));
lua_pushlightuserdata(L, &g_bidiMapKey);
lua_rawget(L, LUA_REGISTRYINDEX);
if (!lua_istable(L, -1)) {
luaL_error(L, "not a table");
}
lua_pushlightuserdata(L, ptrKey);
lua_pushvalue(L, index);
lua_rawset(L, -3);
lua_pop(L, 1);
dbgprint("store_bidi_in_registry end %d\n", lua_gettop(L));
}
///retrieve lua object from the mapping registry and push it on the stack
void get_lua_object_from_registry(lua_State *L, void *ptrKey)
{
dbgprint("get_bidi_from_registry %d\n", lua_gettop(L));
lua_pushlightuserdata(L, &g_bidiMapKey);
lua_rawget(L, LUA_REGISTRYINDEX);
if (!lua_istable(L, -1)) {
luaL_error(L, "not a table");
}
lua_pushlightuserdata(L, ptrKey);
lua_rawget(L, -2);
lua_remove(L, -2);
dbgprint("get_bidi_from_registry end %d\n", lua_gettop(L));
return 1;
}
//dump current lua stack
void stackdump(lua_State* l)
{
int i;
int top = lua_gettop(l);
printf("total in stack %d\n",top);
for (i = 1; i <= top; i++)
{ /* repeat for each level */
int t = lua_type(l, i);
switch (t) {
case LUA_TSTRING: /* strings */
printf("string: '%s'\n", lua_tostring(l, i));
break;
case LUA_TBOOLEAN: /* booleans */
printf("boolean %s\n",lua_toboolean(l, i) ? "true" : "false");
break;
case LUA_TNUMBER: /* numbers */
printf("number: %g\n", lua_tonumber(l, i));
break;
default: /* other values */
printf("%s\n", lua_typename(l, t));
break;
}
printf(" "); /* put a separator */
}
printf("\n"); /* end the listing */
}
//initialize thread local storage
int init_luabdb_tls()
{
int rc = pthread_key_create(&g_luaStateKey, NULL);
return rc;
}
int set_local_lua_state(lua_State *L)
{
return pthread_setspecific(g_luaStateKey, L);
}
lua_State *get_local_lua_state()
{
return (lua_State*) pthread_getspecific(g_luaStateKey);
}