-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathUserdata.h
More file actions
1108 lines (908 loc) · 32.1 KB
/
Userdata.h
File metadata and controls
1108 lines (908 loc) · 32.1 KB
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
// https://github.com/kunitoki/LuaBridge3
// Copyright 2020, kunitoki
// Copyright 2019, Dmitry Tarakanov
// Copyright 2012, Vinnie Falco <vinnie.falco@gmail.com>
// SPDX-License-Identifier: MIT
#pragma once
#include "Config.h"
#include "Errors.h"
#include "LuaException.h"
#include "ClassInfo.h"
#include "TypeTraits.h"
#include "Result.h"
#include "Stack.h"
#include <stdexcept>
#include <type_traits>
namespace luabridge {
namespace detail {
template <class T>
std::error_code getNilBadArgError(lua_State* L, int index)
{
const std::string message = std::string(typeName<T>()) + " expected, got no value";
#if LUABRIDGE_HAS_EXCEPTIONS
if (index > 0 && LuaException::areExceptionsEnabled(L))
{
lua_pushstring(L, message.c_str());
LuaException::raise(L, makeErrorCode(ErrorCode::InvalidTypeCast));
}
#endif
// Lua-call argument path: keep detailed bad-argument text when exceptions are disabled.
if (index > 0)
luaL_argerror(L, lua_absindex(L, index), message.c_str());
return makeErrorCode(ErrorCode::InvalidTypeCast);
}
//=================================================================================================
/**
* @brief Return the identity pointer for our lightuserdata tokens.
*
* Because of Lua's dynamic typing and our improvised system of imposing C++ class structure, there is the possibility that executing
* scripts may knowingly or unknowingly cause invalid data to get passed to the C functions created by LuaBridge.
*
* In particular, our security model addresses the following:
*
* 1. Scripts cannot create a userdata (ignoring the debug lib).
*
* 2. Scripts cannot create a lightuserdata (ignoring the debug lib).
*
* 3. Scripts cannot set the metatable on a userdata.
*/
/**
* @brief Interface to a class pointer retrievable from a userdata.
*/
class Userdata
{
private:
//=============================================================================================
/**
* @brief Validate and retrieve a Userdata on the stack.
*
* The Userdata must exactly match the corresponding class table or const table, or else a Lua error is raised. This is used for the
* __gc metamethod.
*/
static Userdata* getExactClass(lua_State* L, int index, const void* classKey)
{
return (void)classKey, static_cast<Userdata*>(lua_touserdata(L, lua_absindex(L, index)));
}
//=============================================================================================
/**
* @brief Validate and retrieve a Userdata on the stack.
*
* The Userdata must be derived from or the same as the given base class, identified by the key. If canBeConst is false, generates
* an error if the resulting Userdata represents to a const object. We do the type check first so that the error message is informative.
*/
static std::error_code getClassErrorCode(lua_State* L, const void* registryClassKey)
{
lua_rawgetp_x(L, LUA_REGISTRYINDEX, registryClassKey);
const bool classIsRegistered = lua_istable(L, -1);
lua_pop(L, 1);
return makeErrorCode(classIsRegistered ? ErrorCode::InvalidTypeCast : ErrorCode::ClassNotRegistered);
}
static std::error_code getBadArgError(lua_State* L, int index, const void* registryClassKey)
{
const int absIndex = lua_absindex(L, index);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, registryClassKey); // Stack: registry metatable (rt) | nil
const bool classIsRegistered = lua_istable(L, -1);
const char* expected = "unregistered class";
if (classIsRegistered)
{
lua_rawgetp_x(L, -1, getTypeKey()); // Stack: rt, registry type
if (lua_isstring(L, -1))
expected = lua_tostring(L, -1);
lua_pop(L, 1); // Stack: rt
}
const char* got = nullptr;
if (lua_isuserdata(L, absIndex))
{
lua_getmetatable(L, absIndex); // Stack: rt | nil, ot | nil
if (lua_istable(L, -1))
{
lua_rawgetp_x(L, -1, getTypeKey()); // Stack: rt | nil, ot, object type | nil
if (lua_isstring(L, -1))
got = lua_tostring(L, -1);
lua_pop(L, 1); // Stack: rt | nil, ot
}
lua_pop(L, 1); // Stack: rt | nil
}
if (! got)
got = lua_typename(L, lua_type(L, absIndex));
lua_pop(L, 1); // Stack: -
const auto errorCode = classIsRegistered ? ErrorCode::InvalidTypeCast : ErrorCode::ClassNotRegistered;
#if LUABRIDGE_HAS_EXCEPTIONS
if (LuaException::areExceptionsEnabled(L))
{
const std::string message = std::string(expected) + " expected, got " + got;
lua_pushstring(L, message.c_str());
LuaException::raise(L, makeErrorCode(errorCode));
}
#endif
return makeErrorCode(errorCode);
}
static TypeResult<Userdata*> getClass(lua_State* L,
int index,
const void* registryConstKey,
const void* registryClassKey,
bool canBeConst)
{
const int result = lua_getmetatable(L, index); // Stack: object metatable (ot) | nil
if (result == 0 || !lua_istable(L, -1))
{
if (result != 0)
lua_pop(L, 1);
return getBadArgError(L, index, registryClassKey);
}
lua_rawgetp_x(L, -1, getConstKey()); // Stack: ot | nil, const table (co) | nil
LUABRIDGE_ASSERT(lua_istable(L, -1) || lua_isnil(L, -1));
// If const table is NOT present, object is const. Use non-const registry table
// if object cannot be const, so constness validation is done automatically.
// E.g. nonConstFn (constObj)
// -> canBeConst = false, isConst = true
// -> 'Class' registry table, 'const Class' object table
// -> 'expected Class, got const Class'
const bool isConst = lua_isnil(L, -1); // Stack: ot | nil, nil, rt
lua_rawgetp_x(L, LUA_REGISTRYINDEX, (isConst && canBeConst)
? registryConstKey
: registryClassKey); // Stack: ot, co | nil, rt
lua_insert(L, -3); // Stack: rt, ot, co | nil
lua_pop(L, 1); // Stack: rt, ot
for (;;)
{
if (lua_rawequal(L, -1, -2)) // Stack: rt, ot
{
lua_pop(L, 2); // Stack: -
return static_cast<Userdata*>(lua_touserdata(L, index));
}
// Replace current metatable with it's base class.
lua_rawgetp_x(L, -1, getParentKey()); // Stack: rt, ot, parent ot (pot) | nil
if (lua_isnil(L, -1)) // Stack: rt, ot, nil
{
// Drop the object metatable because it may be some parent metatable
lua_pop(L, 3); // Stack: -
return getBadArgError(L, index, registryClassKey);
}
lua_remove(L, -2); // Stack: rt, pot
}
unreachable();
}
static bool isInstance(lua_State* L, int index, const void* registryKey)
{
const auto result = lua_getmetatable(L, index); // Stack: object metatable (ot) | nil
if (result == 0)
return false;
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // Stack: -
return false;
}
lua_rawgetp_x(L, LUA_REGISTRYINDEX, registryKey); // Stack: ot, rt
lua_insert(L, -2); // Stack: rt, ot
for (;;)
{
if (lua_rawequal(L, -1, -2)) // Stack: rt, ot
{
lua_pop(L, 2); // Stack: -
return true;
}
// Replace current metatable with it's base class.
lua_rawgetp_x(L, -1, getParentKey()); // Stack: rt, ot, parent ot (pot) | nil
if (lua_isnil(L, -1)) // Stack: rt, ot, nil
{
// Drop the object metatable because it may be some parent metatable
lua_pop(L, 3); // Stack: -
return false;
}
lua_remove(L, -2); // Stack: rt, pot
}
unreachable();
}
public:
virtual ~Userdata() {}
//=============================================================================================
/**
* @brief Returns the Userdata* if the class on the Lua stack matches.
*
* If the class does not match, a Lua error is raised.
*
* @tparam T A registered user class.
*
* @param L A Lua state.
* @param index The index of an item on the Lua stack.
*
* @return A userdata pointer if the class matches.
*/
template <class T>
static Userdata* getExact(lua_State* L, int index)
{
return getExactClass(L, index, detail::getClassRegistryKey<T>());
}
//=============================================================================================
/**
* @brief Get a pointer to the class from the Lua stack.
*
* If the object is not the class or a subclass, or it violates the const-ness, a Lua error is raised.
*
* @tparam T A registered user class.
*
* @param L A Lua state.
* @param index The index of an item on the Lua stack.
* @param canBeConst TBD
*
* @return A pointer if the class and constness match.
*/
template <class T>
static TypeResult<T*> get(lua_State* L, int index, bool canBeConst)
{
if (lua_isnil(L, index))
return nullptr;
const int absIndex = lua_absindex(L, index);
const auto classId = detail::getClassRegistryKey<T>();
const auto constId = detail::getConstRegistryKey<T>();
// Common-case fast path: exact class/const metatable match.
// This avoids parent-chain traversal and registry table lookups.
if (lua_getmetatable(L, absIndex) && lua_istable(L, -1))
{
lua_rawgetp_x(L, -1, detail::getTypeIdentityKey());
const void* identity = lua_touserdata(L, -1);
lua_pop(L, 1);
if (identity == classId || (canBeConst && identity == constId))
{
lua_pop(L, 1);
return static_cast<T*>(static_cast<Userdata*>(lua_touserdata(L, absIndex))->getPointer());
}
lua_pop(L, 1);
}
auto clazz = getClass(L, absIndex, constId, classId, canBeConst);
if (! clazz)
return clazz.error();
return static_cast<T*>((*clazz)->getPointer());
}
template <class T>
static bool isInstance(lua_State* L, int index)
{
return isInstance(L, index, detail::getClassRegistryKey<T>())
|| isInstance(L, index, detail::getConstRegistryKey<T>());
}
protected:
Userdata() = default;
/**
* @brief Get an untyped pointer to the contained class.
*/
void* getPointer() const noexcept
{
return m_p;
}
void* m_p = nullptr; // subclasses must set this
};
//=================================================================================================
/**
* @brief Wraps a class object stored in a Lua userdata.
*
* The lifetime of the object is managed by Lua. The object is constructed inside the userdata using placement new.
*/
template <class T>
class UserdataValue : public Userdata
{
using AlignType = typename std::conditional_t<alignof(T) <= alignof(double), T, void*>;
static constexpr int MaxPadding = alignof(T) <= alignof(AlignType) ? 0 : alignof(T) - alignof(AlignType) + 1;
public:
UserdataValue(const UserdataValue&) = delete;
UserdataValue operator=(const UserdataValue&) = delete;
~UserdataValue()
{
if (getPointer() != nullptr)
{
getObject()->~T();
}
}
/**
* @brief Push a T via placement new.
*
* The caller is responsible for calling placement new using the returned uninitialized storage.
*
* @param L A Lua state.
*
* @return An object referring to the newly created userdata value.
*/
static UserdataValue<T>* place(lua_State* L, std::error_code& ec)
{
auto* ud = new (lua_newuserdata_x<UserdataValue<T>>(L, sizeof(UserdataValue<T>))) UserdataValue<T>();
lua_rawgetp_x(L, LUA_REGISTRYINDEX, detail::getClassRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
ud->~UserdataValue<T>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
ec = throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
ec = makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
return nullptr;
}
lua_setmetatable(L, -2);
return ud;
}
/**
* @brief Push T via copy construction from U.
*
* @tparam U A container type.
*
* @param L A Lua state.
* @param u A container object l-value reference.
* @param ec Error code that will be set in case of failure to push on the lua stack.
*/
template <class U>
static auto push(lua_State* L, const U& u) -> std::enable_if_t<std::is_copy_constructible_v<U>, Result>
{
std::error_code ec;
auto* ud = place(L, ec);
if (!ud)
return ec;
new (ud->getObject()) U(u);
ud->commit();
return {};
}
/**
* @brief Push T via move construction from U.
*
* @tparam U A container type.
*
* @param L A Lua state.
* @param u A container object r-value reference.
* @param ec Error code that will be set in case of failure to push on the lua stack.
*/
template <class U>
static auto push(lua_State* L, U&& u) -> std::enable_if_t<std::is_move_constructible_v<U>, Result>
{
std::error_code ec;
auto* ud = place(L, ec);
if (!ud)
return ec;
new (ud->getObject()) U(std::move(u));
ud->commit();
return {};
}
/**
* @brief Confirm object construction.
*/
void commit() noexcept
{
m_p = getObject();
}
T* getObject() noexcept
{
// If this fails to compile it means you forgot to provide
// a Container specialization for your container!
if constexpr (MaxPadding == 0)
return reinterpret_cast<T*>(&m_storage[0]);
else
return reinterpret_cast<T*>(&m_storage[0] + m_storage[sizeof(m_storage) - 1]);
}
private:
/**
* @brief Used for placement construction.
*/
UserdataValue() noexcept
: Userdata()
{
if constexpr (MaxPadding > 0)
{
uintptr_t offset = reinterpret_cast<uintptr_t>(&m_storage[0]) % alignof(T);
if (offset > 0)
offset = alignof(T) - offset;
assert(offset < MaxPadding);
m_storage[sizeof(m_storage) - 1] = static_cast<unsigned char>(offset);
}
}
alignas(AlignType) unsigned char m_storage[sizeof(T) + MaxPadding];
};
//=================================================================================================
/**
* @brief Wraps a pointer to a class object inside a Lua userdata.
*
* The lifetime of the object is managed by C++.
*/
class UserdataPtr : public Userdata
{
public:
UserdataPtr(const UserdataPtr&) = delete;
UserdataPtr operator=(const UserdataPtr&) = delete;
/**
* @brief Push non-const pointer to object.
*
* @tparam T A user registered class.
*
* @param L A Lua state.
* @param p A pointer to the user class instance.
* @param ec Error code that will be set in case of failure to push on the lua stack.
*/
template <class T>
static Result push(lua_State* L, T* ptr)
{
if (ptr)
return push(L, ptr, getClassRegistryKey<T>());
lua_pushnil(L);
return {};
}
/**
* @brief Push const pointer to object.
*
* @tparam T A user registered class.
*
* @param L A Lua state.
* @param p A pointer to the user class instance.
* @param ec Error code that will be set in case of failure to push on the lua stack.
*/
template <class T>
static Result push(lua_State* L, const T* ptr)
{
if (ptr)
return push(L, ptr, getConstRegistryKey<T>());
lua_pushnil(L);
return {};
}
private:
/**
* @brief Push a pointer to object using metatable key.
*/
static Result push(lua_State* L, const void* ptr, const void* key)
{
auto* udptr = new (lua_newuserdata_x<UserdataPtr>(L, sizeof(UserdataPtr))) UserdataPtr(const_cast<void*>(ptr));
lua_rawgetp_x(L, LUA_REGISTRYINDEX, key);
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
udptr->~UserdataPtr();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
return throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
return makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
}
lua_setmetatable(L, -2);
return {};
}
explicit UserdataPtr(void* ptr)
{
// Can't construct with a null object!
LUABRIDGE_ASSERT(ptr != nullptr);
m_p = ptr;
}
};
//============================================================================
/**
* @brief Wraps an external value type to a class object inside a Lua userdata.
*
* The lifetime of the object is managed by Lua. The object is constructed inside the userdata using an
* already constructed object provided externally, and it is destructed by a deallocator function provided.
*/
template <class T>
class UserdataValueExternal : public Userdata
{
public:
UserdataValueExternal(const UserdataValueExternal&) = delete;
UserdataValueExternal operator=(const UserdataValueExternal&) = delete;
~UserdataValueExternal()
{
if (getObject() != nullptr)
m_dealloc(getObject());
}
/**
* @brief Push a T via externally allocated object.
*
* @param L A Lua state.
* @param obj The object allocated externally that need to be stored.
* @param dealloc A deallocator function that will free the passed object.
*
* @return An object referring to the newly created userdata value.
*/
template <class Dealloc>
static UserdataValueExternal<T>* place(lua_State* L, T* obj, Dealloc dealloc, std::error_code& ec)
{
auto* ud = new (lua_newuserdata_x<UserdataValueExternal<T>>(L, sizeof(UserdataValueExternal<T>))) UserdataValueExternal<T>(obj, dealloc);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, detail::getClassRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
ud->~UserdataValueExternal<T>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
ec = throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
ec = makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
return nullptr;
}
lua_setmetatable(L, -2);
return ud;
}
T* getObject() noexcept
{
return static_cast<T*>(m_p);
}
private:
UserdataValueExternal(void* ptr, void (*dealloc)(T*)) noexcept
{
// Can't construct with a null object!
LUABRIDGE_ASSERT(ptr != nullptr);
m_p = ptr;
// Can't construct with a null deallocator!
LUABRIDGE_ASSERT(dealloc != nullptr);
m_dealloc = dealloc;
}
void (*m_dealloc)(T*) = nullptr;
};
//============================================================================
/**
* @brief Wraps a container that references a class object.
*
* The template argument C is the container type, ContainerTraits must be specialized on C or else a compile error will result.
*/
template <class C>
class UserdataShared : public Userdata
{
public:
UserdataShared(const UserdataShared&) = delete;
UserdataShared& operator=(const UserdataShared&) = delete;
~UserdataShared() = default;
/**
* @brief Construct from a container to the class or a derived class.
*
* @tparam U A container type.
*
* @param u A container object reference.
*/
template <class U>
explicit UserdataShared(const U& u) : m_c(u)
{
m_p = const_cast<void*>(reinterpret_cast<const void*>((ContainerTraits<C>::get(m_c))));
}
/**
* @brief Construct from a pointer to the class or a derived class.
*
* @tparam U A container type.
*
* @param u A container object pointer.
*/
template <class U>
explicit UserdataShared(U* u) : m_c(u)
{
m_p = const_cast<void*>(reinterpret_cast<const void*>((ContainerTraits<C>::get(m_c))));
}
private:
C m_c;
};
//=================================================================================================
/**
* @brief SFINAE helper for non-const objects.
*/
template <class C, bool MakeObjectConst>
struct UserdataSharedHelper
{
using T = std::remove_const_t<typename ContainerTraits<C>::Type>;
static Result push(lua_State* L, const C& c)
{
if (ContainerTraits<C>::get(c) != nullptr)
{
auto* us = new (lua_newuserdata_x<UserdataShared<C>>(L, sizeof(UserdataShared<C>))) UserdataShared<C>(c);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, getClassRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
us->~UserdataShared<C>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
return throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
return makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
}
lua_setmetatable(L, -2);
}
else
{
lua_pushnil(L);
}
return {};
}
static Result push(lua_State* L, T* t)
{
if (t)
{
auto* us = new (lua_newuserdata_x<UserdataShared<C>>(L, sizeof(UserdataShared<C>))) UserdataShared<C>(t);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, getClassRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
us->~UserdataShared<C>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
return throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
return makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
}
lua_setmetatable(L, -2);
}
else
{
lua_pushnil(L);
}
return {};
}
};
/**
* @brief SFINAE helper for const objects.
*/
template <class C>
struct UserdataSharedHelper<C, true>
{
using T = std::remove_const_t<typename ContainerTraits<C>::Type>;
static Result push(lua_State* L, const C& c)
{
if (ContainerTraits<C>::get(c) != nullptr)
{
auto* us = new (lua_newuserdata_x<UserdataShared<C>>(L, sizeof(UserdataShared<C>))) UserdataShared<C>(c);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, getConstRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
us->~UserdataShared<C>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
return throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
return makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
}
lua_setmetatable(L, -2);
}
else
{
lua_pushnil(L);
}
return {};
}
static Result push(lua_State* L, T* t)
{
if (t)
{
auto* us = new (lua_newuserdata_x<UserdataShared<C>>(L, sizeof(UserdataShared<C>))) UserdataShared<C>(t);
lua_rawgetp_x(L, LUA_REGISTRYINDEX, getConstRegistryKey<T>());
if (!lua_istable(L, -1))
{
lua_pop(L, 1); // possibly: a nil
us->~UserdataShared<C>();
#if LUABRIDGE_RAISE_UNREGISTERED_CLASS_USAGE
return throw_or_error_code<LuaException>(L, ErrorCode::ClassNotRegistered);
#else
return makeErrorCode(ErrorCode::ClassNotRegistered);
#endif
}
lua_setmetatable(L, -2);
}
else
{
lua_pushnil(L);
}
return {};
}
};
//=================================================================================================
/**
* @brief Pass by container.
*
* The container controls the object lifetime. Typically this will be a lifetime shared by C++ and Lua using a reference count. Because of type
* erasure, containers like std::shared_ptr will not work, unless the type hold by them is derived from std::enable_shared_from_this.
*/
template <class T, bool ByContainer>
struct StackHelper
{
using ReturnType = TypeResult<T>;
static Result push(lua_State* L, const T& t)
{
return UserdataSharedHelper<T, std::is_const_v<typename ContainerTraits<T>::Type>>::push(L, t);
}
static ReturnType get(lua_State* L, int index)
{
using CastType = std::remove_const_t<typename ContainerTraits<T>::Type>;
auto result = Userdata::get<CastType>(L, index, true);
if (! result)
return result.error();
return ContainerTraits<T>::construct(*result);
}
};
/**
* @brief Pass by value.
*
* Lifetime is managed by Lua. A C++ function which accesses a pointer or reference to an object outside the activation record in which it was
* retrieved may result in undefined behavior if Lua garbage collected it.
*/
template <class T>
struct StackHelper<T, false>
{
static Result push(lua_State* L, const T& t)
{
return UserdataValue<T>::push(L, t);
}
static Result push(lua_State* L, T&& t)
{
return UserdataValue<T>::push(L, std::move(t));
}
static TypeResult<std::reference_wrapper<const T>> get(lua_State* L, int index)
{
auto result = Userdata::get<T>(L, index, true);
if (! result)
return result.error(); // nil passed to reference
if (*result == nullptr)
return getNilBadArgError<T>(L, index);
return std::cref(**result);
}
};
//=================================================================================================
/**
* @brief Lua stack conversions for pointers and references to class objects.
*
* Lifetime is managed by C++. Lua code which remembers a reference to the value may result in undefined behavior if C++ destroys the object.
* The handling of the const and volatile qualifiers happens in UserdataPtr.
*/
template <class C, bool ByContainer>
struct RefStackHelper
{
using ReturnType = TypeResult<C>;
using T = std::remove_const_t<typename ContainerTraits<C>::Type>;
static Result push(lua_State* L, const C& t)
{
return UserdataSharedHelper<C, std::is_const_v<typename ContainerTraits<C>::Type>>::push(L, t);
}
static ReturnType get(lua_State* L, int index)
{
auto result = Userdata::get<T>(L, index, true);
if (! result)
return result.error();
return ContainerTraits<C>::construct(*result);
}
};
template <class T>
struct RefStackHelper<T, false>
{
using ReturnType = TypeResult<std::reference_wrapper<T>>;
static Result push(lua_State* L, T& t)
{
return UserdataPtr::push(L, std::addressof(t));
}
static Result push(lua_State* L, const T& t)
{
return UserdataPtr::push(L, std::addressof(t));
}
static ReturnType get(lua_State* L, int index)
{
auto result = Userdata::get<T>(L, index, true);
if (! result)
return result.error(); // nil passed to reference
if (*result == nullptr)
return getNilBadArgError<T>(L, index);
return std::ref(**result);
}
};
//=================================================================================================
/**
* @brief Trait class that selects whether to return a user registered class object by value or by reference.
*/
template <class T, class Enable = void>
struct UserdataGetter
{
using ReturnType = TypeResult<T*>;
static ReturnType get(lua_State* L, int index)
{
auto result = Userdata::get<T>(L, index, true);
if (! result)
return result.error();
return *result;
}
};
template <class T>
struct UserdataGetter<T, std::void_t<T (*)()>>
{
using ReturnType = TypeResult<T>;
static ReturnType get(lua_State* L, int index)
{
auto result = StackHelper<T, IsContainer<T>::value>::get(L, index);
if (! result)
return result.error();
return *result;
}
};
} // namespace detail
//=================================================================================================
/**
* @brief Lua stack conversions for class objects passed by value.
*/
template <class T, class = void>
struct Stack
{
using IsUserdata = void;
using Getter = detail::UserdataGetter<T>;
using ReturnType = typename Getter::ReturnType;
[[nodiscard]] static Result push(lua_State* L, const T& value)
{
return detail::StackHelper<T, detail::IsContainer<T>::value>::push(L, value);
}