-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathCFunctions.h
More file actions
2505 lines (2056 loc) · 75.9 KB
/
CFunctions.h
File metadata and controls
2505 lines (2056 loc) · 75.9 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 "ClassInfo.h"
#include "Errors.h"
#include "FuncTraits.h"
#include "LuaHelpers.h"
#include "Options.h"
#include "Stack.h"
#include "TypeTraits.h"
#include "Userdata.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <optional>
#include <string>
namespace luabridge {
class LuaRef;
namespace detail {
//=================================================================================================
/**
* @brief Make argument lists extracting them from the lua state, starting at a stack index.
*
* @tparam ArgsPack Arguments pack to extract from the lua stack.
* @tparam Start Start index where stack variables are located in the lua stack.
*/
template <class T>
auto unwrap_argument_or_error(lua_State* L, std::size_t index, std::size_t start)
{
auto result = Stack<T>::get(L, static_cast<int>(index + start));
if (result)
return std::move(*result);
// TODO - this might be costly, how to deal with it ?
if constexpr (! std::is_lvalue_reference_v<T>)
{
using U = std::reference_wrapper<std::remove_reference_t<T>>;
auto resultRef = Stack<U>::get(L, static_cast<int>(index));
if (resultRef)
return (*resultRef).get();
}
raise_lua_error(L, "Error decoding argument #%d: %s", static_cast<int>(index + 1), result.message().c_str());
unreachable();
}
template <class ArgsPack, std::size_t Start, std::size_t... Indices>
auto make_arguments_list_impl([[maybe_unused]] lua_State* L, std::index_sequence<Indices...>)
{
return tupleize(unwrap_argument_or_error<std::tuple_element_t<Indices, ArgsPack>>(L, Indices, Start)...);
}
template <class ArgsPack, std::size_t Start>
auto make_arguments_list(lua_State* L)
{
return make_arguments_list_impl<ArgsPack, Start>(L, std::make_index_sequence<std::tuple_size_v<ArgsPack>>());
}
//=================================================================================================
/**
* @brief Helpers for iterating through tuple arguments, pushing each argument to the lua stack.
*/
template <std::size_t Index = 0, class... Types>
auto push_arguments(lua_State*, std::tuple<Types...>)
-> std::enable_if_t<Index == sizeof...(Types), std::tuple<Result, std::size_t>>
{
return std::make_tuple(Result(), Index + 1);
}
template <std::size_t Index = 0, class... Types>
auto push_arguments(lua_State* L, std::tuple<Types...> t)
-> std::enable_if_t<Index < sizeof...(Types), std::tuple<Result, std::size_t>>
{
using T = std::tuple_element_t<Index, std::tuple<Types...>>;
auto result = Stack<T>::push(L, std::get<Index>(t));
if (! result)
return std::make_tuple(result, Index + 1);
return push_arguments<Index + 1, Types...>(L, std::move(t));
}
//=================================================================================================
/**
* @brief Helpers for iterating through tuple arguments, popping each argument from the lua stack.
*/
template <std::ptrdiff_t Start, std::ptrdiff_t Index = 0, class... Types>
auto pop_arguments(lua_State*, std::tuple<Types...>&)
-> std::enable_if_t<Index == sizeof...(Types), std::size_t>
{
return sizeof...(Types);
}
template <std::ptrdiff_t Start, std::ptrdiff_t Index = 0, class... Types>
auto pop_arguments(lua_State* L, std::tuple<Types...>& t)
-> std::enable_if_t<Index < sizeof...(Types), std::size_t>
{
using T = std::tuple_element_t<Index, std::tuple<Types...>>;
std::get<Index>(t) = Stack<T>::get(L, Start - Index);
return pop_arguments<Start, Index + 1, Types...>(L, t);
}
//=================================================================================================
/**
* @brief Check if a method name is a metamethod.
*/
template <class T = void, class... Args>
constexpr auto make_array(Args&&... args)
{
if constexpr (std::is_same_v<void, T>)
return std::array<std::common_type_t<std::decay_t<Args>...>, sizeof...(Args)>{{ std::forward<Args>(args)... }};
else
return std::array<T, sizeof...(Args)>{{ std::forward<Args>(args)... }};
}
inline bool is_metamethod(std::string_view method_name)
{
static constexpr auto metamethods = make_array<std::string_view>(
"__add",
"__band",
"__bnot",
"__bor",
"__bxor",
"__call",
"__close",
"__concat",
"__div",
"__eq",
"__gc",
"__idiv",
"__index",
"__ipairs",
"__le",
"__len",
"__lt",
"__metatable",
"__mod",
"__mode",
"__mul",
"__name",
"__newindex",
"__pairs",
"__pow",
"__shl",
"__shr",
"__sub",
"__tostring",
"__unm"
);
if (method_name.size() <= 2 || method_name[0] != '_' || method_name[1] != '_')
return false;
auto result = std::lower_bound(metamethods.begin(), metamethods.end(), method_name);
return result != metamethods.end() && *result == method_name;
}
/**
* @brief Make super method name.
*/
inline std::string make_super_method_name(const char* name)
{
LUABRIDGE_ASSERT(name != nullptr);
return (std::string_view(name).find("_") == 0u)
? (std::string("super") + name)
: (std::string("super_") + name);
}
//=================================================================================================
/**
* @brief Make super method name.
*/
inline Options get_class_options(lua_State* L, int index)
{
LUABRIDGE_ASSERT(lua_istable(L, index)); // Stack: mt
Options options = defaultOptions;
lua_rawgetp_x(L, index, getClassOptionsKey()); // Stack: mt, ifb (may be nil)
if (lua_isnumber(L, -1))
options = Options::fromUnderlying(lua_tointeger(L, -1));
lua_pop(L, 1);
return options;
}
//=================================================================================================
/**
* @brief Push class or const table onto stack.
*/
inline void push_class_or_const_table(lua_State* L, int index)
{
LUABRIDGE_ASSERT(lua_istable(L, index)); // Stack: mt
lua_rawgetp_x(L, index, getClassKey()); // Stack: mt, class table (ct) | nil
if (! lua_istable(L, -1)) // Stack: mt, nil
{
lua_pop(L, 1); // Stack: mt
lua_rawgetp_x(L, index, getConstKey()); // Stack: mt, const table (co) | nil
if (! lua_istable(L, -1)) // Stack: mt, nil
return;
}
}
//=================================================================================================
/**
* @brief __index metamethod for a namespace or class static and non-static members.
*
* Retrieves functions from metatables and properties from propget tables. Looks through the class hierarchy if inheritance is present.
*/
inline std::optional<int> try_call_index_fallback(lua_State* L)
{
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
lua_rawgetp_x(L, -1, getIndexFallbackKey()); // Stack: mt, ifb (may be nil)
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
lua_pushvalue(L, 1); // Stack: mt, ifb, arg1
lua_pushvalue(L, 2); // Stack: mt, ifb, arg1, arg2
lua_call(L, 2, 1); // Stack: mt, ifbresult
if (! lua_isnoneornil(L, -1))
{
lua_remove(L, -2); // Stack: ifbresult
return 1;
}
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
inline std::optional<int> try_call_static_index_fallback(lua_State* L)
{
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
lua_rawgetp_x(L, -1, getStaticIndexFallbackKey()); // Stack: mt, ifb (may be nil)
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
lua_pushvalue(L, 2); // Stack: mt, ifb, arg1 (key only, no self for static)
lua_call(L, 1, 1); // Stack: mt, ifbresult
if (! lua_isnoneornil(L, -1))
{
lua_remove(L, -2); // Stack: ifbresult
return 1;
}
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
template <bool IsObject>
inline std::optional<int> try_call_index_extensible(lua_State* L, const char* key)
{
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
if constexpr (IsObject)
push_class_or_const_table(L, -1); // Stack: mt, cl | co
else
lua_rawgetp_x(L, -1, getStaticKey()); // Stack: mt, st
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, cl | co | st
rawgetfield(L, -1, key); // Stack: mt, st, ifbresult | nil
if (! lua_isnoneornil(L, -1)) // Stack: mt, cl | co | st, ifbresult
{
lua_remove(L, -2); // Stack: mt, ifbresult
lua_remove(L, -2); // Stack: ifbresult
return 1;
}
lua_pop(L, 2); // Stack: mt
return std::nullopt;
}
template <bool IsObject>
inline int index_metamethod(lua_State* L)
{
#if LUABRIDGE_SAFE_STACK_CHECKS
luaL_checkstack(L, 3, detail::error_lua_stack_overflow);
#endif
LUABRIDGE_ASSERT(lua_istable(L, 1) || lua_isuserdata(L, 1)); // Stack (further not shown): table | userdata, name
lua_getmetatable(L, 1); // Stack: class/const table (mt)
LUABRIDGE_ASSERT(lua_istable(L, -1));
// Protect internal meta methods
const char* key = lua_tostring(L, 2);
if (key != nullptr && is_metamethod(key))
{
lua_pushnil(L);
return 1;
}
for (;;)
{
if constexpr (IsObject)
{
// Repeat the lookup in the index fallback
if (auto result = try_call_index_fallback(L))
return *result;
}
else
{
// Repeat the lookup in the static index fallback
if (auto result = try_call_static_index_fallback(L))
return *result;
}
// Search into self or metatable
if (lua_istable(L, 1))
{
if constexpr (IsObject)
lua_pushvalue(L, 1); // Stack: mt, self
else
push_class_or_const_table(L, -1); // Stack: mt, cl | co
if (lua_istable(L, -1))
{
lua_pushvalue(L, 2); // Stack: mt, self | cl | co, field name
lua_rawget(L, -2); // Stack: mt, self | cl | co, field | nil
lua_remove(L, -2); // Stack: mt, field | nil
if (! lua_isnil(L, -1)) // Stack: mt, field
{
lua_remove(L, -2); // Stack: field
return 1;
}
}
lua_pop(L, 1); // Stack: mt
}
lua_pushvalue(L, 2); // Stack: mt, field name
lua_rawget(L, -2); // Stack: mt, field | nil
if (! lua_isnil(L, -1)) // Stack: mt, field
{
lua_remove(L, -2); // Stack: field
return 1;
}
LUABRIDGE_ASSERT(lua_isnil(L, -1)); // Stack: mt, nil
lua_pop(L, 1); // Stack: mt
// Repeat the lookup in the index extensible, for method overrides
const Options options = get_class_options(L, -1); // Stack: mt
if (options.test(extensibleClass | allowOverridingMethods))
{
if (auto result = try_call_index_extensible<IsObject>(L, key))
return *result;
}
// Try in the propget key
lua_rawgetp_x(L, -1, getPropgetKey()); // Stack: mt, propget table (pg)
LUABRIDGE_ASSERT(lua_istable(L, -1));
lua_pushvalue(L, 2); // Stack: mt, pg, field name
lua_rawget(L, -2); // Stack: mt, pg, getter | nil
lua_remove(L, -2); // Stack: mt, getter | nil
if (lua_iscfunction(L, -1)) // Stack: mt, getter
{
lua_remove(L, -2); // Stack: getter
lua_pushvalue(L, 1); // Stack: getter, table | userdata
lua_call(L, 1, 1); // Stack: value
return 1;
}
LUABRIDGE_ASSERT(lua_isnil(L, -1)); // Stack: mt, nil
lua_pop(L, 1); // Stack: mt
// It may mean that the field may be in const table and it's constness violation.
// Repeat the lookup in the parent metafield, or fallback to extensible class check.
lua_rawgetp_x(L, -1, getParentKey()); // Stack: mt, parent mt | nil
if (lua_isnil(L, -1)) // Stack: mt, nil
{
lua_pop(L, 2); // Stack: -
break;
}
// Remove the metatable and repeat the search in the parent one.
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, parent mt
lua_remove(L, -2); // Stack: parent mt
}
lua_getmetatable(L, 1); // Stack: class/const table (mt)
LUABRIDGE_ASSERT(lua_istable(L, -1));
for (;;)
{
const Options options = get_class_options(L, -1); // Stack: mt
if (options.test(extensibleClass | ~allowOverridingMethods))
{
if (auto result = try_call_index_extensible<IsObject>(L, key))
return *result;
}
// Repeat the lookup in the parent metafield, or return nil if the field doesn't exist.
lua_rawgetp_x(L, -1, getParentKey()); // Stack: mt, parent mt | nil
if (lua_isnil(L, -1)) // Stack: mt, nil
{
lua_remove(L, -2); // Stack: nil
return 1;
}
// Remove the metatable and repeat the search in the parent one.
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, parent mt
lua_remove(L, -2); // Stack: parent mt
}
// no return
}
template <bool IsObject>
inline int index_metamethod_simple(lua_State* L)
{
#if LUABRIDGE_SAFE_STACK_CHECKS
luaL_checkstack(L, 3, detail::error_lua_stack_overflow);
#endif
LUABRIDGE_ASSERT(lua_istable(L, 1) || lua_isuserdata(L, 1));
// Fast path for simple userdata objects: when registration provides propget and
// method tables as closure upvalues, avoid metatable/pointer-key lookups.
if constexpr (IsObject)
{
if (lua_isuserdata(L, 1))
{
const char* key = lua_tostring(L, 2);
const auto rawlookup = [L](int tableIndex)
{
lua_pushvalue(L, 2);
lua_rawget(L, tableIndex);
};
rawlookup(lua_upvalueindex(1)); // Stack: getter | nil
if (lua_iscfunction(L, -1))
{
lua_pushvalue(L, 1); // Stack: getter, self
lua_call(L, 1, 1); // Stack: value
return 1;
}
lua_pop(L, 1);
if (key != nullptr && is_metamethod(key))
{
lua_pushnil(L);
return 1;
}
rawlookup(lua_upvalueindex(2)); // Stack: value | nil
if (! lua_isnil(L, -1))
return 1;
lua_pop(L, 1);
lua_pushnil(L);
return 1;
}
}
else
{
// Fast path for simple static tables: capture propget/class/metatable as upvalues.
if (lua_istable(L, 1))
{
const char* key = lua_tostring(L, 2);
const auto rawlookup = [L](int tableIndex)
{
lua_pushvalue(L, 2);
lua_rawget(L, tableIndex);
};
if (key != nullptr && is_metamethod(key))
{
lua_pushnil(L);
return 1;
}
if (lua_istable(L, lua_upvalueindex(2)))
{
rawlookup(lua_upvalueindex(2)); // Stack: value | nil
if (! lua_isnil(L, -1))
return 1;
lua_pop(L, 1);
}
rawlookup(lua_upvalueindex(3)); // Stack: value | nil
if (! lua_isnil(L, -1))
return 1;
lua_pop(L, 1);
rawlookup(lua_upvalueindex(1)); // Stack: getter | nil
if (lua_iscfunction(L, -1))
{
lua_pushvalue(L, 1); // Stack: getter, self
lua_call(L, 1, 1); // Stack: value
return 1;
}
lua_pop(L, 1);
lua_pushnil(L);
return 1;
}
}
lua_getmetatable(L, 1); // Stack: mt
LUABRIDGE_ASSERT(lua_istable(L, -1));
const char* key = lua_tostring(L, 2);
const auto rawlookup = [L]()
{
lua_pushvalue(L, 2);
lua_rawget(L, -2);
};
// For userdata instance property access, checking propget first avoids an always-miss lookup
// in the class table for common property keys.
if (lua_isuserdata(L, 1))
{
lua_rawgetp_x(L, -1, getPropgetKey()); // Stack: mt, pg
LUABRIDGE_ASSERT(lua_istable(L, -1));
rawlookup(); // Stack: mt, pg, getter | nil
lua_remove(L, -2); // Stack: mt, getter | nil
if (lua_iscfunction(L, -1))
{
lua_remove(L, -2); // Stack: getter
lua_pushvalue(L, 1); // Stack: getter, self
lua_call(L, 1, 1); // Stack: value
return 1;
}
lua_pop(L, 1); // Stack: mt
}
if (key != nullptr && is_metamethod(key))
{
lua_pushnil(L);
return 1;
}
if (lua_istable(L, 1))
{
if constexpr (IsObject)
lua_pushvalue(L, 1); // Stack: mt, self
else
push_class_or_const_table(L, -1); // Stack: mt, cl | co
if (lua_istable(L, -1))
{
rawlookup(); // Stack: mt, self | cl | co, value | nil
lua_remove(L, -2); // Stack: mt, value | nil
if (! lua_isnil(L, -1))
{
lua_remove(L, -2); // Stack: value
return 1;
}
}
lua_pop(L, 1); // Stack: mt
}
rawlookup(); // Stack: mt, value | nil
if (! lua_isnil(L, -1))
{
lua_remove(L, -2); // Stack: value
return 1;
}
lua_pop(L, 1); // Stack: mt
lua_rawgetp_x(L, -1, getPropgetKey()); // Stack: mt, pg
LUABRIDGE_ASSERT(lua_istable(L, -1));
rawlookup(); // Stack: mt, pg, getter | nil
lua_remove(L, -2); // Stack: mt, getter | nil
if (lua_iscfunction(L, -1))
{
lua_remove(L, -2); // Stack: getter
lua_pushvalue(L, 1); // Stack: getter, self
lua_call(L, 1, 1); // Stack: value
return 1;
}
lua_pop(L, 2); // Stack: -
lua_pushnil(L);
return 1;
}
//=================================================================================================
/**
* @brief __newindex metamethod for non-static members.
*
* Retrieves properties from propset tables.
*/
inline std::optional<int> try_call_newindex_fallback(lua_State* L)
{
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
lua_rawgetp_x(L, -1, getNewIndexFallbackKey()); // Stack: mt, nifb (may be nil)
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
lua_pushvalue(L, 1); // stack: mt, nifb, arg1
lua_pushvalue(L, 2); // stack: mt, nifb, arg1, arg2
lua_pushvalue(L, 3); // stack: mt, nifb, arg1, arg2, arg3
lua_call(L, 3, 0); // stack: mt
return 0;
}
inline std::optional<int> try_call_static_newindex_fallback(lua_State* L)
{
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
lua_rawgetp_x(L, -1, getStaticNewIndexFallbackKey()); // Stack: mt, nifb (may be nil)
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
lua_pushvalue(L, 2); // stack: mt, nifb, arg1 (key only, no self for static)
lua_pushvalue(L, 3); // stack: mt, nifb, arg1, arg2 (value)
lua_call(L, 2, 0); // stack: mt
return 0;
}
inline std::optional<int> try_call_newindex_extensible(lua_State* L, const char* key)
{
LUABRIDGE_ASSERT(key != nullptr);
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt
// For Lua function values (instance methods added from Lua), capture the originating class
// table so the method is stored there rather than in a traversed-to parent class table.
// This prevents e.g. `function Derived:init()` from polluting `Base`'s method table.
//
// For non-function values (static properties like `Class.prop = val`), the original
// traversal-end behaviour is preserved: storing them in the nearest class table that
// already has a matching key (or the topmost base if none exists). This keeps static
// properties out of the derived class table, which is also used for instance extensible
// method lookup, avoiding unintended shadowing of per-instance properties accessed via an
// index-fallback metamethod registered on a non-extensible base class.
const bool value_is_function = lua_isfunction(L, 3);
if (value_is_function)
{
// Capture the original (most-derived) class table — always write here.
push_class_or_const_table(L, -1); // Stack: mt, orig_ct | nil
if (! lua_istable(L, -1)) // Stack: mt, nil
{
lua_pop(L, 1); // Stack: mt
return std::nullopt;
}
// Stack: mt, orig_ct
lua_pushvalue(L, -2); // Stack: mt, orig_ct, cur_mt (traversal copy)
for (;;)
{
push_class_or_const_table(L, -1); // Stack: mt, orig_ct, cur_mt, cur_ct | nil
if (! lua_istable(L, -1)) // Stack: mt, orig_ct, cur_mt, nil
{
lua_pop(L, 2); // Stack: mt, orig_ct
break;
}
lua_pushvalue(L, 2); // Stack: mt, orig_ct, cur_mt, cur_ct, field name
lua_rawget(L, -2); // Stack: mt, orig_ct, cur_mt, cur_ct, field | nil
if (! lua_isnil(L, -1)) // Stack: mt, orig_ct, cur_mt, cur_ct, field
{
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 3); // Stack: mt, orig_ct
break;
}
const Options options = get_class_options(L, -2); // Stack: mt, orig_ct, cur_mt, cur_ct, field
if (! options.test(allowOverridingMethods))
luaL_error(L, "immutable member '%s'", key);
// Store super_ alias in the ORIGINAL (derived) class table so only derived
// instances can call it; the base class table is left completely untouched.
rawsetfield(L, -4, make_super_method_name(key).c_str()); // Stack: mt, orig_ct, cur_mt, cur_ct
lua_pop(L, 2); // Stack: mt, orig_ct
break;
}
lua_pop(L, 1); // Stack: mt, orig_ct, cur_mt, cur_ct
lua_rawgetp_x(L, -2, getParentKey()); // Stack: mt, orig_ct, cur_mt, cur_ct, pmt | nil
if (lua_isnil(L, -1)) // Stack: mt, orig_ct, cur_mt, cur_ct, nil
{
lua_pop(L, 3); // Stack: mt, orig_ct
break;
}
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, orig_ct, cur_mt, cur_ct, pmt
lua_remove(L, -2); // Stack: mt, orig_ct, cur_mt, pmt
lua_remove(L, -2); // Stack: mt, orig_ct, pmt
}
// Stack: mt, orig_ct — write to the original (most-derived) class table.
lua_getmetatable(L, -1); // Stack: mt, orig_ct, orig_ct_mt
lua_pushvalue(L, 3); // Stack: mt, orig_ct, orig_ct_mt, arg3
rawsetfield(L, -2, key); // Stack: mt, orig_ct, orig_ct_mt
lua_pop(L, 2); // Stack: mt
return 0;
}
// Non-function value (static property): use original traversal-end write location.
lua_pushvalue(L, -1); // Stack: mt, mt
for (;;)
{
push_class_or_const_table(L, -1); // Stack: mt, mt, ct | nil
if (! lua_istable(L, -1)) // Stack: mt, mt, nil
{
lua_pop(L, 2); // Stack: mt
return std::nullopt;
}
lua_pushvalue(L, 2); // Stack: mt, mt, ct, field name
lua_rawget(L, -2); // Stack: mt, mt, ct, field | nil
if (! lua_isnil(L, -1)) // Stack: mt, mt, ct, field
{
if (! lua_iscfunction(L, -1))
{
lua_pop(L, 1);
break;
}
const Options options = get_class_options(L, -2); // Stack: mt, mt, ct, field
if (! options.test(allowOverridingMethods))
luaL_error(L, "immutable member '%s'", key);
rawsetfield(L, -2, make_super_method_name(key).c_str()); // Stack: mt, mt, ct
break;
}
lua_pop(L, 1); // Stack: mt, mt, ct
lua_rawgetp_x(L, -2, getParentKey()); // Stack: mt, mt, ct, pmt | nil
if (lua_isnil(L, -1)) // Stack: mt, mt, ct, nil
{
lua_pop(L, 1); // Stack: mt, mt, ct
break;
}
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, mt, ct, pmt
lua_remove(L, -2); // Stack: mt, mt, pmt
lua_remove(L, -2); // Stack: mt, pmt
}
lua_remove(L, -2); // Stack: mt, ct
lua_getmetatable(L, -1); // Stack: mt, ct, ct_mt
lua_pushvalue(L, 3); // Stack: mt, ct, ct_mt, arg3
rawsetfield(L, -2, key); // Stack: mt, ct, ct_mt
lua_pop(L, 2); // Stack: mt
return 0;
}
template <bool IsObject>
inline int newindex_metamethod(lua_State* L)
{
#if LUABRIDGE_SAFE_STACK_CHECKS
luaL_checkstack(L, 3, detail::error_lua_stack_overflow);
#endif
LUABRIDGE_ASSERT(lua_istable(L, 1) || lua_isuserdata(L, 1)); // Stack (further not shown): table | userdata, name, new value
lua_getmetatable(L, 1); // Stack: metatable (mt)
LUABRIDGE_ASSERT(lua_istable(L, -1));
const char* key = lua_tostring(L, 2);
for (;;)
{
const Options options = get_class_options(L, -1);
// Try in the property set table
lua_rawgetp_x(L, -1, getPropsetKey()); // Stack: mt, propset table (ps) | nil
if (lua_isnil(L, -1)) // Stack: mt, nil
luaL_error(L, "no member named '%s'", key);
LUABRIDGE_ASSERT(lua_istable(L, -1));
lua_pushvalue(L, 2); // Stack: mt, ps, field name
lua_rawget(L, -2); // Stack: mt, ps, setter | nil
lua_remove(L, -2); // Stack: mt, setter | nil
if (lua_iscfunction(L, -1)) // Stack: mt, setter
{
lua_remove(L, -2); // Stack: setter
if constexpr (IsObject)
lua_pushvalue(L, 1); // Stack: setter, table | userdata
lua_pushvalue(L, 3); // Stack: setter, table | userdata, new value
lua_call(L, IsObject ? 2 : 1, 0); // Stack: -
return 0;
}
LUABRIDGE_ASSERT(lua_isnil(L, -1)); // Stack: mt, nil
lua_pop(L, 1); // Stack: mt
if constexpr (IsObject)
{
// Try in the new index fallback
if (auto result = try_call_newindex_fallback(L))
return *result;
}
else
{
// Try in the static new index fallback
if (auto result = try_call_static_newindex_fallback(L))
return *result;
// Try in the new index extensible
if (options.test(extensibleClass))
{
if (auto result = try_call_newindex_extensible(L, key))
return *result;
}
}
// Try in the parent
lua_rawgetp_x(L, -1, getParentKey()); // Stack: mt, parent mt | nil
if (lua_isnil(L, -1)) // Stack: mt, nil
luaL_error(L, "no writable member '%s'", key);
LUABRIDGE_ASSERT(lua_istable(L, -1)); // Stack: mt, parent mt
lua_remove(L, -2); // Stack: parent mt
// Repeat the search in the parent
}
return 0;
}
template <bool IsObject>
inline int newindex_metamethod_simple(lua_State* L)
{
#if LUABRIDGE_SAFE_STACK_CHECKS
luaL_checkstack(L, 3, detail::error_lua_stack_overflow);
#endif
LUABRIDGE_ASSERT(lua_istable(L, 1) || lua_isuserdata(L, 1));
// Fast path for simple userdata objects: propset table is captured as upvalue.
if constexpr (IsObject)
{
if (lua_isuserdata(L, 1))
{
const char* key = lua_tostring(L, 2);
if (! lua_istable(L, lua_upvalueindex(1)))
luaL_error(L, "no writable member '%s'", key);
lua_pushvalue(L, 2); // Stack: key
lua_rawget(L, lua_upvalueindex(1)); // Stack: setter | nil
if (lua_iscfunction(L, -1))
{
lua_pushvalue(L, 1); // Stack: setter, self
lua_pushvalue(L, 3); // Stack: setter, self, value
lua_call(L, 2, 0);
return 0;
}
luaL_error(L, "no writable member '%s'", key);
}
}
else
{
// Fast path for simple static tables: propset table is captured as upvalue.
if (lua_istable(L, 1))
{
const char* key = lua_tostring(L, 2);
if (! lua_istable(L, lua_upvalueindex(1)))
luaL_error(L, "no writable member '%s'", key);
lua_pushvalue(L, 2); // Stack: key
lua_rawget(L, lua_upvalueindex(1)); // Stack: setter | nil
if (lua_iscfunction(L, -1))
{
lua_pushvalue(L, 3); // Stack: setter, value
lua_call(L, 1, 0);
return 0;
}
luaL_error(L, "no writable member '%s'", key);
}
}
lua_getmetatable(L, 1); // Stack: mt
LUABRIDGE_ASSERT(lua_istable(L, -1));
const char* key = lua_tostring(L, 2);
lua_rawgetp_x(L, -1, getPropsetKey()); // Stack: mt, ps | nil
if (! lua_istable(L, -1))
luaL_error(L, "no member named '%s'", key);
lua_pushvalue(L, 2); // Stack: mt, ps, key
lua_rawget(L, -2); // Stack: mt, ps, setter | nil
lua_remove(L, -2); // Stack: mt, setter | nil
if (lua_iscfunction(L, -1))
{
lua_remove(L, -2); // Stack: setter
if constexpr (IsObject)
lua_pushvalue(L, 1); // Stack: setter, self
lua_pushvalue(L, 3); // Stack: setter, self, value
lua_call(L, IsObject ? 2 : 1, 0);
return 0;
}
luaL_error(L, "no writable member '%s'", key);
}
//=================================================================================================
/**
* @brief lua_CFunction to report an error writing to a read-only value.
*
* The name of the variable is in the first upvalue.
*/
inline int read_only_error(lua_State* L)
{
raise_lua_error(L, "'%s' is read-only", lua_tostring(L, lua_upvalueindex(1)));
return 0;
}
//=================================================================================================
/**
* @brief __tostring metamethod for a class.
*/
template <class C>
int tostring_metamethod(lua_State* L)
{
const void* ptr = lua_topointer(L, 1);
lua_getmetatable(L, -1); // Stack: metatable (mt)
lua_rawgetp_x(L, -1, getTypeKey()); // Stack: mt, classname (cn)
lua_remove(L, -2); // Stack: cn
std::stringstream ss;
ss << ": 0x" << std::hex << reinterpret_cast<std::uintptr_t>(const_cast<void*>(ptr));
lua_pushstring(L, ss.str().c_str()); // Stack: cn, address string (astr)
lua_concat(L, 2); // Stack: astr
return 1;
}
//=================================================================================================
/**
* @brief __destruct metamethod for a class.