forked from svarog2741/xrluafix
-
Notifications
You must be signed in to change notification settings - Fork 3
/
LibStr.cpp
64 lines (57 loc) · 1.52 KB
/
LibStr.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
#include "pch.hpp"
#include "LibStr.h"
#include <cctype>
static int str_trim(lua_State* L)
{
size_t size;
const char* front = luaL_checklstring(L, 1, &size);
const char* end = &front[size - 1];
for (; size && std::isspace(*front); size--, front++) {}
for (; size && std::isspace(*end); size--, end--) {}
lua_pushlstring(L, front, (size_t)(end - front) + 1);
return 1;
}
static int str_trim_l(lua_State* L)
{
size_t size;
const char* front = luaL_checklstring(L, 1, &size);
const char* end = &front[size - 1];
for (; size && std::isspace(*front); size--, front++) {}
lua_pushlstring(L, front, (size_t)(end - front) + 1);
return 1;
}
static int str_trim_r(lua_State* L)
{
size_t size;
const char* front = luaL_checklstring(L, 1, &size);
const char* end = &front[size - 1];
for (; size && std::isspace(*end); size--, end--) {}
lua_pushlstring(L, front, (size_t)(end - front) + 1);
return 1;
}
static int str_trim_w(lua_State* L)
{
int i = 0;
const char* s = luaL_checkstring(L, 1);
while (s[i] == ' ')
i++;
const int n = i;
while (s[i] != ' ' && s[i])
i++;
const int d = i - n;
lua_pushlstring(L, s + n, d);
return 1;
}
int open_string(lua_State* L)
{
constexpr luaL_Reg strlib[] =
{
{ "trim", str_trim },
{ "trim_l", str_trim_l },
{ "trim_r", str_trim_r },
{ "trim_w", str_trim_w },
{nullptr, nullptr }
};
luaL_openlib(L, LUA_STRLIBNAME, strlib, 0);
return 0;
}