-
Notifications
You must be signed in to change notification settings - Fork 13
/
helper.h
102 lines (86 loc) · 3.67 KB
/
helper.h
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
/* SPDX-License-Identifier: MIT */
/*
* Author: Jianhui Zhao <[email protected]>
*/
#ifndef __ECO_HELPER_H
#define __ECO_HELPER_H
#include <lauxlib.h>
#include <stdbool.h>
#include <stdint.h>
#ifndef likely
#define likely(x) (__builtin_expect(((x) != 0), 1))
#endif
#ifndef unlikely
#define unlikely(x) (__builtin_expect(((x) != 0), 0))
#endif
#ifndef container_of
#define container_of(ptr, type, member) \
({ \
const __typeof__(((type *) NULL)->member) *__mptr = (ptr); \
(type *) ((char *) __mptr - offsetof(type, member)); \
})
#endif
#define stack_dump(L) \
do { \
int top = lua_gettop(L); \
int i; \
printf("--------stack dump--------\n"); \
for (i = 1; i <= top; i++) { \
int t = lua_type(L, i); \
printf("%2d: ", i); \
switch (t) { \
case LUA_TSTRING: \
printf("'%s'", lua_tostring(L, i)); \
break; \
case LUA_TBOOLEAN: \
printf(lua_toboolean(L, i) ? "true" : "false"); \
break; \
case LUA_TNUMBER: \
printf("%g", lua_tonumber(L, i)); \
break; \
case LUA_TLIGHTUSERDATA: \
printf("%p", lua_topointer(L, i)); \
break; \
default: \
printf("%s", lua_typename(L, t)); \
break; \
} \
printf(" "); \
} \
printf("\n"); \
printf("++++++++++++++++++++++++++\n"); \
} while (0)
#define lua_add_constant(L, n, v) \
do { \
lua_pushinteger(L, (v)); \
lua_setfield(L, -2, (n)); \
} while (0)
#define lua_gettablelen(L, idx) \
({ \
int index = lua_absindex(L, (idx)); \
int cnt = 0; \
lua_pushnil(L); \
while (lua_next(L, index)) { \
cnt++; \
lua_pop(L, 1); \
} \
cnt; \
})
#define lua_table_is_array(L, idx) lua_gettablelen(L, (idx)) == lua_rawlen(L, (idx))
static inline void eco_new_metatable(lua_State *L, const char *name, const struct luaL_Reg regs[])
{
const struct luaL_Reg *reg;
if (!luaL_newmetatable(L, name))
return;
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
if (!regs)
return;
reg = regs;
while (reg->name) {
lua_pushcfunction(L, reg->func);
lua_setfield(L, -2, reg->name);
reg++;
}
}
#endif