-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlua_wrapper.hpp
2492 lines (2085 loc) · 75 KB
/
lua_wrapper.hpp
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if !defined(NEKO_LUA_WRAPPER_HPP)
#define NEKO_LUA_WRAPPER_HPP
#include <bit>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <string>
#include <tuple> // std::ignore
#include <typeindex>
#include <utility>
#include <variant>
#include <vector>
#include "lua_wrapper_pp.hpp"
#include "luax.h"
#include "utils.hpp"
namespace std {
template <typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
constexpr std::underlying_type_t<E> to_underlying(E e) noexcept {
return static_cast<std::underlying_type_t<E>>(e);
}
} // namespace std
namespace neko {
namespace reflection {
template <unsigned short N>
struct cstring {
constexpr explicit cstring(std::string_view str) noexcept : cstring{str, std::make_integer_sequence<unsigned short, N>{}} {}
constexpr const char *data() const noexcept { return chars_; }
constexpr unsigned short size() const noexcept { return N; }
constexpr operator std::string_view() const noexcept { return {data(), size()}; }
template <unsigned short... I>
constexpr cstring(std::string_view str, std::integer_sequence<unsigned short, I...>) noexcept : chars_{str[I]..., '\0'} {}
char chars_[static_cast<size_t>(N) + 1];
};
template <>
struct cstring<0> {
constexpr explicit cstring(std::string_view) noexcept {}
constexpr const char *data() const noexcept { return nullptr; }
constexpr unsigned short size() const noexcept { return 0; }
constexpr operator std::string_view() const noexcept { return {}; }
};
template <typename T>
constexpr auto name_raw() noexcept {
#if defined(__clang__) || defined(__GNUC__)
std::string_view name = __PRETTY_FUNCTION__;
size_t start = name.find('=') + 2;
size_t end = name.size() - 1;
return std::string_view{name.data() + start, end - start};
#elif defined(_MSC_VER)
std::string_view name = __FUNCSIG__;
size_t start = name.find('<') + 1;
size_t end = name.rfind(">(");
name = std::string_view{name.data() + start, end - start};
start = name.find(' ');
return start == std::string_view::npos ? name : std::string_view{name.data() + start + 1, name.size() - start - 1};
#else
#error Unsupported compiler
#endif
}
template <typename T>
constexpr auto name() noexcept {
constexpr auto name = name_raw<T>();
return cstring<name.size()>{name};
}
template <typename T>
constexpr auto name_v = name<T>();
struct DummyFlag {};
template <typename Enum, typename T, Enum enumValue>
inline int get_enum_value(std::map<int, std::string> &values) {
#if defined _MSC_VER && !defined __clang__
std::string func(__FUNCSIG__);
std::string mark = "DummyFlag";
auto pos = func.find(mark) + mark.size();
std::string enumStr = func.substr(pos);
auto start = enumStr.find_first_not_of(", ");
auto end = enumStr.find('>');
if (start != enumStr.npos && end != enumStr.npos && enumStr[start] != '(') {
enumStr = enumStr.substr(start, end - start);
values.insert({(int)enumValue, enumStr});
}
#else // gcc, clang
std::string func(__PRETTY_FUNCTION__);
std::string mark = "enumValue = ";
auto pos = func.find(mark) + mark.size();
std::string enumStr = func.substr(pos, func.size() - pos - 1);
char ch = enumStr[0];
if (!(ch >= '0' && ch <= '9') && ch != '(') values.insert({(int)enumValue, enumStr});
#endif
return 0;
}
template <typename Enum, int min_value, int... ints>
void guess_enum_range(std::map<int, std::string> &values, const std::integer_sequence<int, ints...> &) {
auto dummy = {get_enum_value<Enum, DummyFlag, (Enum)(ints + min_value)>(values)...};
}
template <typename Enum, int... ints>
void guess_enum_bit_range(std::map<int, std::string> &values, const std::integer_sequence<int, ints...> &) {
auto dummy = {get_enum_value<Enum, DummyFlag, (Enum)0>(values), get_enum_value<Enum, DummyFlag, (Enum)(1 << (int)ints)>(values)...};
}
template <typename T>
auto GetTypeName() {
return reflection::name_v<T>.data();
}
template <typename T>
struct wrapper {
T a;
};
template <typename T>
wrapper(T) -> wrapper<T>;
template <typename T>
static inline T storage = {};
template <auto T>
constexpr auto main_name_of_pointer() {
constexpr auto is_identifier = [](char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; };
#if __GNUC__ && (!__clang__) && (!_MSC_VER)
std::string_view str = __PRETTY_FUNCTION__;
std::size_t start = str.rfind("::") + 2;
std::size_t end = start;
for (; end < str.size() && is_identifier(str[end]); end++) {
}
return str.substr(start, end - start);
#elif __clang__
std::string_view str = __PRETTY_FUNCTION__;
std::size_t start = str.rfind(".") + 1;
std::size_t end = start;
for (; end < str.size() && is_identifier(str[end]); end++) {
}
return str.substr(start, end - start);
#elif _MSC_VER
std::string_view str = __FUNCSIG__;
std::size_t start = str.rfind("->") + 2;
std::size_t end = start;
for (; end < str.size() && is_identifier(str[end]); end++) {
}
return str.substr(start, end - start);
#else
static_assert(false, "Not supported compiler");
#endif
}
// 无定义 我们需要一个可以转换为任何类型的在以下特殊语境中使用的辅助类
struct __Any {
constexpr __Any(int) {}
template <typename T>
requires std::is_copy_constructible_v<T>
constexpr operator T &() const;
template <typename T>
requires std::is_move_constructible_v<T>
constexpr operator T &&() const;
template <typename T>
requires(!std::is_copy_constructible_v<T> && !std::is_move_constructible_v<T>)
constexpr operator T() const;
};
// 计算结构体成员数量
#if !defined(_MSC_VER) || 0 // 我不知道为什么 if constexpr (!requires { T{Args...}; }) {...} 方法会导致目前版本的vs代码感知非常卡
template <typename T>
consteval size_t struct_size(auto &&...Args) {
if constexpr (!requires { T{Args...}; }) {
return sizeof...(Args) - 1;
} else {
return struct_size<T>(Args..., __any{});
}
}
template <class T>
struct struct_member_count : std::integral_constant<std::size_t, struct_size<T>()> {};
#else
template <typename T, typename = void, typename... Ts>
struct struct_size {
constexpr static size_t value = sizeof...(Ts) - 1;
};
template <typename T, typename... Ts>
struct struct_size<T, std::void_t<decltype(T{Ts{}...})>, Ts...> {
constexpr static size_t value = struct_size<T, void, Ts..., __Any>::value;
};
template <class T>
struct struct_member_count : std::integral_constant<std::size_t, struct_size<T>::value> {};
#endif
template <typename T, std::size_t N>
constexpr std::size_t try_initialize_with_n() {
return []<std::size_t... Is>(std::index_sequence<Is...>) { return requires { T{__Any(Is)...}; }; }(std::make_index_sequence<N>{});
}
template <typename T, std::size_t N = 0>
constexpr auto field_count_impl() {
if constexpr (try_initialize_with_n<T, N>() && !try_initialize_with_n<T, N + 1>()) {
return N;
} else {
return field_count_impl<T, N + 1>();
}
}
struct UniversalType {
template <typename T>
operator T();
};
template <typename T, typename... Args>
consteval auto memberCount() {
static_assert(std::is_aggregate_v<std::remove_cvref_t<T>>);
if constexpr (requires { T{{Args{}}..., {UniversalType{}}}; } == false) {
return sizeof...(Args);
} else {
return memberCount<T, Args..., UniversalType>();
}
}
// template <typename T>
// requires std::is_aggregate_v<T>
// static constexpr auto field_count = field_count_impl<T>();
template <typename T>
requires std::is_aggregate_v<T>
static constexpr auto field_count = memberCount<T>();
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4101)
#endif
#define STRUCT_FIELD_TYPE_DEF(N) \
template <typename T, std::size_t I> \
constexpr auto __struct_field_type_impl(T my_struct, std::integral_constant<std::size_t, N>) { \
auto [NEKO_PP_PARAMS(x, N)] = my_struct; \
return std::type_identity<std::tuple_element_t<I, std::tuple<NEKO_PP_CALL_PARAMS(decltype, x, N)>>>{}; \
}
NEKO_PP_FOR_EACH(STRUCT_FIELD_TYPE_DEF, 63)
template <typename T, std::size_t I>
constexpr auto field_type_impl(T object) {
constexpr auto N = field_count<T>;
return __struct_field_type_impl<T, I>(object, std::integral_constant<std::size_t, N>{});
}
#define STRUCT_FIELD_ACCESS_DEF(N) \
template <std::size_t I> \
constexpr auto &&__struct_field_access_impl(auto &&my_struct, std::integral_constant<std::size_t, N>) { \
auto &&[NEKO_PP_PARAMS(x, N)] = std::forward<decltype(my_struct)>(my_struct); \
return std::get<I>(std::forward_as_tuple(NEKO_PP_PARAMS(x, N))); \
}
NEKO_PP_FOR_EACH(STRUCT_FIELD_ACCESS_DEF, 63)
template <std::size_t I>
constexpr auto &&field_access(auto &&object) {
using T = std::remove_cvref_t<decltype(object)>;
constexpr auto N = field_count<T>;
return __struct_field_access_impl<I>(object, std::integral_constant<std::size_t, N>{});
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
template <typename T, std::size_t I>
constexpr auto field_name_impl() noexcept {
constexpr auto name = main_name_of_pointer<wrapper{&field_access<I>(storage<T>)}>();
return cstring<name.size()>{name};
}
template <typename T, std::size_t I>
requires std::is_aggregate_v<T>
using field_type = typename decltype(field_type_impl<T, I>(std::declval<T>()))::type;
template <typename T, std::size_t I>
requires std::is_aggregate_v<T>
static constexpr auto field_name = field_name_impl<T, I>();
} // namespace reflection
namespace luabind {
#define PRELOAD(name, function) \
lua_getglobal(L, "package"); \
lua_getfield(L, -1, "preload"); \
lua_pushcfunction(L, function); \
lua_setfield(L, -2, name); \
lua_pop(L, 2)
void luax_run_bootstrap(lua_State *L);
void luax_run_nekogame(lua_State *L);
i32 luax_require_script(lua_State *L, String filepath);
inline lua_Integer luax_len(lua_State *L, i32 arg) {
lua_len(L, arg);
lua_Integer len = luaL_checkinteger(L, -1);
lua_pop(L, 1);
return len;
}
inline void luax_geti(lua_State *L, i32 arg, lua_Integer n) {
lua_pushinteger(L, n);
lua_gettable(L, arg);
}
// 将表值设置在堆栈顶部
inline void luax_set_number_field(lua_State *L, const char *key, lua_Number n) {
lua_pushnumber(L, n);
lua_setfield(L, -2, key);
}
inline void luax_set_int_field(lua_State *L, const char *key, lua_Integer n) {
lua_pushinteger(L, n);
lua_setfield(L, -2, key);
}
inline void luax_set_string_field(lua_State *L, const char *key, const char *str) {
lua_pushstring(L, str);
lua_setfield(L, -2, key);
}
// 从表中获取值
inline lua_Number luax_number_field(lua_State *L, i32 arg, const char *key) {
lua_getfield(L, arg, key);
lua_Number num = luaL_checknumber(L, -1);
lua_pop(L, 1);
return num;
}
inline lua_Number luax_opt_number_field(lua_State *L, i32 arg, const char *key, lua_Number fallback) {
i32 type = lua_getfield(L, arg, key);
lua_Number num = fallback;
if (type != LUA_TNIL) {
num = luaL_optnumber(L, -1, fallback);
}
lua_pop(L, 1);
return num;
}
inline lua_Integer luax_int_field(lua_State *L, i32 arg, const char *key) {
lua_getfield(L, arg, key);
lua_Integer num = luaL_checkinteger(L, -1);
lua_pop(L, 1);
return num;
}
inline lua_Number luax_opt_int_field(lua_State *L, i32 arg, const char *key, lua_Number fallback) {
i32 type = lua_getfield(L, arg, key);
lua_Number num = fallback;
if (type != LUA_TNIL) {
num = luaL_optinteger(L, -1, fallback);
}
lua_pop(L, 1);
return num;
}
inline String luax_string_field(lua_State *L, i32 arg, const char *key) {
lua_getfield(L, arg, key);
size_t len = 0;
char *str = (char *)luaL_checklstring(L, -1, &len);
lua_pop(L, 1);
return {str, len};
}
inline String luax_opt_string_field(lua_State *L, i32 arg, const char *key, const char *fallback) {
lua_getfield(L, arg, key);
size_t len = 0;
char *str = (char *)luaL_optlstring(L, -1, fallback, &len);
lua_pop(L, 1);
return {str, len};
}
inline bool luax_boolean_field(lua_State *L, i32 arg, const char *key, bool fallback = false) {
i32 type = lua_getfield(L, arg, key);
bool b = fallback;
if (type != LUA_TNIL) {
b = lua_toboolean(L, -1);
}
lua_pop(L, 1);
return b;
}
inline String luax_check_string(lua_State *L, i32 arg) {
size_t len = 0;
char *str = (char *)luaL_checklstring(L, arg, &len);
return {str, len};
}
inline String luax_opt_string(lua_State *L, i32 arg, String def) { return lua_isstring(L, arg) ? luax_check_string(L, arg) : def; }
inline void luax_new_class(lua_State *L, const char *mt_name, const luaL_Reg *l) {
luaL_newmetatable(L, mt_name);
luaL_setfuncs(L, l, 0);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
}
enum {
LUAX_UD_TNAME = 1,
LUAX_UD_PTR_SIZE = 2,
};
#if !defined(NEKO_LUAJIT)
template <typename T>
void luax_new_userdata(lua_State *L, T data, const char *tname) {
void *new_udata = lua_newuserdatauv(L, sizeof(T), 2);
lua_pushstring(L, tname);
lua_setiuservalue(L, -2, LUAX_UD_TNAME);
lua_pushnumber(L, sizeof(T));
lua_setiuservalue(L, -2, LUAX_UD_PTR_SIZE);
memcpy(new_udata, &data, sizeof(T));
luaL_setmetatable(L, tname);
}
#else
template <typename T>
void luax_new_userdata(lua_State *L, T data, const char *tname) {
T *new_udata = (T *)lua_newuserdata(L, sizeof(T));
// 为用户数据设置元表
luaL_getmetatable(L, tname);
lua_setmetatable(L, -2);
memcpy(new_udata, &data, sizeof(T));
// 额外的值使用lua_setfield将其存储在表中
lua_newtable(L);
lua_pushstring(L, tname);
lua_setfield(L, -2, "tname");
lua_pushnumber(L, sizeof(T));
lua_setfield(L, -2, "size");
// 将这个表作为用户数据的环境表存储
lua_setfenv(L, -2);
}
#endif
#define luax_ptr_userdata luax_new_userdata
struct LuaNil {};
template <typename T, typename I>
constexpr bool check_integral_limit(I i) {
static_assert(std::is_integral_v<I>);
static_assert(std::is_integral_v<T>);
static_assert(sizeof(I) >= sizeof(T));
if constexpr (sizeof(I) == sizeof(T)) {
return true;
} else if constexpr (std::numeric_limits<I>::is_signed == std::numeric_limits<T>::is_signed) {
return i >= std::numeric_limits<T>::lowest() && i <= (std::numeric_limits<T>::max)();
} else if constexpr (std::numeric_limits<I>::is_signed) {
return static_cast<std::make_unsigned_t<I>>(i) >= std::numeric_limits<T>::lowest() && static_cast<std::make_unsigned_t<I>>(i) <= (std::numeric_limits<T>::max)();
} else {
return static_cast<std::make_signed_t<I>>(i) >= std::numeric_limits<T>::lowest() && static_cast<std::make_signed_t<I>>(i) <= (std::numeric_limits<T>::max)();
}
}
union lua_maxalign_t {
LUAI_MAXALIGN;
};
constexpr inline size_t lua_maxalign = std::alignment_of_v<lua_maxalign_t>;
template <typename T>
constexpr T *udata_align(void *storage) {
if constexpr (std::alignment_of_v<T> > lua_maxalign) {
uintptr_t mask = (uintptr_t)(std::alignment_of_v<T> - 1);
storage = (void *)(((uintptr_t)storage + mask) & ~mask);
return static_cast<T *>(storage);
} else {
return static_cast<T *>(storage);
}
}
template <typename T>
constexpr T *udata_new(lua_State *L, int nupvalue) {
if constexpr (std::alignment_of_v<T> > lua_maxalign) {
void *storage = lua_newuserdatauv(L, sizeof(T) + std::alignment_of_v<T>, nupvalue);
std::memset(storage, 0, sizeof(T));
return udata_align<T>(storage);
} else {
void *storage = lua_newuserdatauv(L, sizeof(T), nupvalue);
std::memset(storage, 0, sizeof(T));
std::memset(storage, 0, sizeof(T));
return udata_align<T>(storage);
}
}
template <typename T>
T checklightud(lua_State *L, int arg) {
luaL_checktype(L, arg, LUA_TLIGHTUSERDATA);
return tolightud<T>(L, arg);
}
template <typename T>
T &toudata(lua_State *L, int arg) {
return *udata_align<T>(lua_touserdata(L, arg));
}
template <typename T>
T *toudata_ptr(lua_State *L, int arg) {
return udata_align<T>(lua_touserdata(L, arg));
}
template <typename T>
struct udata {};
template <typename T, typename = void>
struct udata_has_nupvalue : std::false_type {};
template <typename T>
struct udata_has_nupvalue<T, std::void_t<decltype(udata<T>::nupvalue)>> : std::true_type {};
template <typename T>
int destroyudata(lua_State *L) {
toudata<T>(L, 1).~T();
return 0;
}
template <typename T>
void getmetatable(lua_State *L) {
if (luaL_newmetatable(L, reflection::name_v<T>.data())) {
if constexpr (!std::is_trivially_destructible<T>::value) {
lua_pushcfunction(L, destroyudata<T>);
lua_setfield(L, -2, "__gc");
}
udata<T>::metatable(L);
}
}
template <typename T, typename... Args>
T &newudata(lua_State *L, Args &&...args) {
int nupvalue = 0;
if constexpr (udata_has_nupvalue<T>::value) {
nupvalue = udata<T>::nupvalue;
}
T *o = udata_new<T>(L, nupvalue);
new (o) T(std::forward<Args>(args)...);
getmetatable<T>(L);
lua_setmetatable(L, -2);
return *o;
}
template <typename T>
T &checkudata(lua_State *L, int arg, const_str tname = reflection::name_v<T>.data()) {
return *udata_align<T>(luaL_checkudata(L, arg, tname));
}
inline std::string_view checkstrview(lua_State *L, int idx) {
size_t len = 0;
const char *buf = luaL_checklstring(L, idx, &len);
return {buf, len};
}
template <typename T, typename I>
constexpr bool checklimit(I i) {
static_assert(std::is_integral_v<I>);
static_assert(std::is_integral_v<T>);
static_assert(sizeof(I) >= sizeof(T));
if constexpr (sizeof(I) == sizeof(T)) {
return true;
} else if constexpr (std::numeric_limits<I>::is_signed == std::numeric_limits<T>::is_signed) {
return i >= std::numeric_limits<T>::lowest() && i <= (std::numeric_limits<T>::max)();
} else if constexpr (std::numeric_limits<I>::is_signed) {
return static_cast<std::make_unsigned_t<I>>(i) >= std::numeric_limits<T>::lowest() && static_cast<std::make_unsigned_t<I>>(i) <= (std::numeric_limits<T>::max)();
} else {
return static_cast<std::make_signed_t<I>>(i) >= std::numeric_limits<T>::lowest() && static_cast<std::make_signed_t<I>>(i) <= (std::numeric_limits<T>::max)();
}
}
template <typename T>
T checkinteger(lua_State *L, int arg) {
static_assert(std::is_trivial_v<T>);
if constexpr (std::is_enum_v<T>) {
using UT = std::underlying_type_t<T>;
return static_cast<T>(checkinteger<UT>(L, arg));
} else if constexpr (std::is_integral_v<T>) {
lua_Integer r = luaL_checkinteger(L, arg);
if constexpr (std::is_same_v<T, lua_Integer>) {
return r;
} else if constexpr (sizeof(T) >= sizeof(lua_Integer)) {
return static_cast<T>(r);
} else {
if (checklimit<T>(r)) {
return static_cast<T>(r);
}
luaL_error(L, "bad argument '#%d' limit exceeded", arg);
// std::unreachable();
neko_assert(0, "unreachable");
}
} else {
return std::bit_cast<T>(checkinteger<lua_Integer>(L, arg));
}
}
template <typename T, T def>
T optinteger(lua_State *L, int arg) {
static_assert(std::is_trivial_v<T>);
if constexpr (std::is_enum_v<T>) {
using UT = std::underlying_type_t<T>;
return static_cast<T>(optinteger<UT, std::to_underlying(def)>(L, arg));
} else if constexpr (std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, lua_Integer>) {
return luaL_optinteger(L, arg, def);
} else if constexpr (sizeof(T) == sizeof(lua_Integer)) {
lua_Integer r = optinteger<lua_Integer, static_cast<lua_Integer>(def)>(L, arg);
return static_cast<T>(r);
} else if constexpr (sizeof(T) < sizeof(lua_Integer)) {
lua_Integer r = optinteger<lua_Integer, static_cast<lua_Integer>(def)>(L, arg);
if (checklimit<T>(r)) {
return static_cast<T>(r);
}
luaL_error(L, "bad argument '#%d' limit exceeded", arg);
// std::unreachable();
neko_assert(0, "unreachable");
} else {
static_assert(checklimit<lua_Integer>(def));
lua_Integer r = optinteger<lua_Integer, static_cast<lua_Integer>(def)>(L, arg);
return static_cast<T>(r);
}
} else {
// If std::bit_cast were not constexpr, it would fail here, so let it fail.
return std::bit_cast<T>(optinteger<lua_Integer, std::bit_cast<lua_Integer>(def)>(L, arg));
}
}
template <typename T>
T tolightud(lua_State *L, int arg) {
if constexpr (std::is_integral_v<T>) {
uintptr_t r = std::bit_cast<uintptr_t>(tolightud<void *>(L, arg));
if constexpr (std::is_same_v<T, uintptr_t>) {
return r;
} else if constexpr (sizeof(T) >= sizeof(uintptr_t)) {
return static_cast<T>(r);
} else {
if (checklimit<T>(r)) {
return static_cast<T>(r);
}
luaL_error(L, "bad argument #%d limit exceeded", arg);
// std::unreachable();
neko_assert(0, "unreachable");
}
} else if constexpr (std::is_same_v<T, void *>) {
return lua_touserdata(L, arg);
} else if constexpr (std::is_pointer_v<T>) {
return static_cast<T>(tolightud<void *>(L, arg));
} else {
return std::bit_cast<T>(tolightud<void *>(L, arg));
}
}
namespace detail {
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_same_v<std::decay_t<T>, LuaNil>
{
lua_pushnil(L);
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_same_v<T, lua_CFunction>
{
lua_pushcfunction(L, x);
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_same_v<T, lua_CFunction>
{
x = lua_tocfunction(L, N);
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_same_v<T, bool>
{
lua_pushboolean(L, x);
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_same_v<T, bool>
{
x = lua_toboolean(L, N);
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_integral_v<T> && !std::is_same_v<T, bool>
{
lua_pushinteger(L, x);
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_integral_v<T> && !std::is_same_v<T, bool>
{
x = static_cast<T>(lua_tointeger(L, N));
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_floating_point_v<T>
{
lua_pushnumber(L, x);
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_floating_point_v<T>
{
x = static_cast<T>(lua_tonumber(L, N));
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_same_v<T, const char *>
{
lua_pushstring(L, x);
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_same_v<T, const char *>
{
x = lua_tostring(L, N);
}
template <typename T>
auto Push(lua_State *L, T x)
requires std::is_same_v<T, std::string>
{
lua_pushstring(L, x.c_str());
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_same_v<T, std::string>
{
x = lua_tostring(L, N);
}
template <typename T, std::size_t N>
auto Push(lua_State *L, T (&arr)[N]) {
lua_newtable(L); // 创建 Lua 表
int i = 0;
for (auto &x : arr) {
lua_pushinteger(L, ++i); // Lua 索引从 1 开始
detail::Push(L, x); // 对单个元素递归调用 Push
lua_settable(L, -3); // 设置键值对
}
}
template <typename T>
auto Get(lua_State *L, int idx, T &arr)
requires std::is_bounded_array_v<T>
{
lua_pushvalue(L, idx);
constexpr std::size_t N = std::extent_v<T>; // 推断数组大小
for (std::size_t i = 0; i < N; ++i) {
lua_pushinteger(L, i + 1);
lua_gettable(L, -2);
detail::Get(L, -1, arr[i]);
lua_pop(L, 1);
}
lua_pop(L, 1);
}
template <typename T>
auto Push(lua_State *L, T &x)
requires std::is_enum_v<T>
{
return detail::Push(L, static_cast<typename std::underlying_type<T>::type>(x));
}
template <typename T>
auto Get(lua_State *L, int N, T &x)
requires std::is_enum_v<T>
{
typename std::underlying_type<T>::type new_x;
detail::Get(L, N, new_x);
x = static_cast<T>(new_x);
}
struct LuaStack {
template <typename T>
static inline void Push(lua_State *L, T &&any) {
detail::Push(L, std::forward<T>(any));
}
template <typename T>
static inline auto Get(lua_State *L, int index, T &value) {
return detail::Get<T>(L, index, value);
}
};
} // namespace detail
namespace detail {
// 自动弹出栈元素 确保数量不变的辅助类
class StackGuard {
public:
explicit StackGuard(lua_State *L) : m_L(L), m_count(::lua_gettop(L)) {}
~StackGuard() {
int n = ::lua_gettop(m_L);
assert(n >= m_count);
if (n > m_count) {
::lua_pop(m_L, (n - m_count));
}
}
private:
lua_State *m_L;
int m_count;
};
} // namespace detail
class LuaRef;
class LuaRefBase {
protected:
lua_State *L;
int m_ref;
struct FromStackIndex {};
// 不应该直接使用
explicit LuaRefBase(lua_State *L, FromStackIndex) : L(L) { m_ref = luaL_ref(L, LUA_REGISTRYINDEX); }
explicit LuaRefBase(lua_State *L, int ref) : L(L), m_ref(ref) {}
~LuaRefBase() { luaL_unref(L, LUA_REGISTRYINDEX, m_ref); }
public:
virtual void Push() const { lua_rawgeti(L, LUA_REGISTRYINDEX, m_ref); }
std::string tostring() const {
lua_getglobal(L, "tostring");
Push();
lua_call(L, 1, 1);
const char *str = lua_tostring(L, 1);
lua_pop(L, 1);
return std::string(str);
}
int Type() const {
int result;
Push();
result = lua_type(L, -1);
lua_pop(L, 1);
return result;
}
inline bool IsNil() const { return Type() == LUA_TNIL; }
inline bool IsNumber() const { return Type() == LUA_TNUMBER; }
inline bool IsString() const { return Type() == LUA_TSTRING; }
inline bool IsTable() const { return Type() == LUA_TTABLE; }
inline bool IsFunction() const { return Type() == LUA_TFUNCTION; }
inline bool IsUserdata() const { return Type() == LUA_TUSERDATA; }
inline bool IsThread() const { return Type() == LUA_TTHREAD; }
inline bool IsLightUserdata() const { return Type() == LUA_TLIGHTUSERDATA; }
inline bool IsBool() const { return Type() == LUA_TBOOLEAN; }
template <typename... Args>
inline LuaRef const operator()(Args... args) const;
template <typename... Args>
inline void Call(int ret, Args... args) const;
template <typename T>
void Append(T v) const {
Push();
size_t len = lua_rawlen(L, -1);
detail::LuaStack::Push(L, v);
lua_rawseti(L, -2, ++len);
lua_pop(L, 1);
}
template <typename T>
T Cast() {
detail::StackGuard p(L);
Push();
T t{};
detail::LuaStack::Get(L, -1, t);
return t;
}
template <typename T>
operator T() {
return Cast<T>();
}
};
template <typename K>
class LuaTableElement : public LuaRefBase {
friend class LuaRef;
private:
K m_key;
public:
LuaTableElement(lua_State *L, K key) : LuaRefBase(L, FromStackIndex()), m_key(key) {}
void Push() const override {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_ref);
detail::LuaStack::Push(L, m_key);
lua_gettable(L, -2);
lua_remove(L, -2);
}
// 为该表/键分配一个新值
template <typename T>
LuaTableElement &operator=(T v) {
detail::StackGuard p(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, m_ref);
detail::LuaStack::Push(L, m_key);
detail::LuaStack::Push(L, v);
lua_settable(L, -3);
return *this;
}
template <typename NK>
LuaTableElement<NK> operator[](NK key) const {
Push();
return LuaTableElement<NK>(L, key);
}
};
namespace detail {
template <typename T>
auto Push(lua_State *L, LuaTableElement<T> const &e) {
e.Push();
}
} // namespace detail
class LuaRef : public LuaRefBase {
friend LuaRefBase;
private:
explicit LuaRef(lua_State *L, FromStackIndex fs) : LuaRefBase(L, fs) {}
public:
LuaRef(lua_State *L) : LuaRefBase(L, LUA_REFNIL) {}
LuaRef(lua_State *L, const std::string &global) : LuaRefBase(L, LUA_REFNIL) {
lua_getglobal(L, global.c_str());
m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
LuaRef(LuaRef const &other) : LuaRefBase(other.L, LUA_REFNIL) {
other.Push();
m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
LuaRef(LuaRef &&other) noexcept : LuaRefBase(other.L, other.m_ref) { other.m_ref = LUA_REFNIL; }
LuaRef &operator=(LuaRef &&other) noexcept {
if (this == &other) return *this;
std::swap(L, other.L);
std::swap(m_ref, other.m_ref);
return *this;
}
LuaRef &operator=(LuaRef const &other) {
if (this == &other) return *this;
luaL_unref(L, LUA_REGISTRYINDEX, m_ref);
other.Push();
L = other.L;
m_ref = luaL_ref(L, LUA_REGISTRYINDEX);
return *this;
}