forked from svarog2741/xrluafix
-
Notifications
You must be signed in to change notification settings - Fork 2
/
LibTab.cpp
100 lines (92 loc) · 1.76 KB
/
LibTab.cpp
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
#include "pch.hpp"
#include "LibTab.h"
#include "LibMath.h"
static int tab_keys(lua_State* L)
{
int i = 1;
luaL_checktype(L, 1, LUA_TTABLE);
lua_newtable(L);
lua_pushnil(L);
while (lua_next(L, 1) != 0)
{
lua_pushinteger(L, i);
++i;
lua_pushvalue(L, -3);
lua_settable(L, 2);
lua_pop(L, 1);
}
return 1;
}
static int tab_values(lua_State* L)
{
int i = 1;
luaL_checktype(L, 1, LUA_TTABLE);
lua_newtable(L);
lua_pushnil(L);
while (lua_next(L, 1) != 0)
{
lua_pushinteger(L, i);
++i;
lua_pushvalue(L, -2);
lua_settable(L, 2);
lua_pop(L, 1);
}
return 1;
}
static int get_size(lua_State* L)
{
int i = 0;
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2);
while (lua_next(L, 1))
{
++i;
lua_pop(L, 1);
}
lua_pushinteger(L, i);
return 1;
}
static int C_get_size(lua_State* L)
{
int i = 0;
lua_settop(L, 2);
while (lua_next(L, 1))
{
++i;
lua_pop(L, 1);
}
return i;
}
static int get_random(lua_State* L)
{
int i = C_get_size(L);
const int j = gen_random_in_range(1, i);
i = 0;
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2);
while (lua_next(L, 1))
{
++i;
if (i == j)
{
lua_pushvalue(L, -2);
lua_pushvalue(L, -2);
return 2;
}
lua_pop(L, 1);
}
return 0;
}
int open_table(lua_State* L)
{
constexpr luaL_Reg tab_funcs[] =
{
{ "keys", tab_keys },
{ "values", tab_values },
{ "size", get_size },
{ "random", get_random },
{ nullptr, nullptr }
};
luaL_openlib(L, LUA_TABLIBNAME, tab_funcs, 0);
return 0;
}