-
Notifications
You must be signed in to change notification settings - Fork 887
/
LuaContext.hpp
2960 lines (2510 loc) · 121 KB
/
LuaContext.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
/*
Copyright (c) 2013, Pierre KRIEGER
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_LUACONTEXT_HPP
#define INCLUDE_LUACONTEXT_HPP
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstring>
#include <functional>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <stdexcept>
#include <string>
#include <sstream>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <boost/any.hpp>
#include <boost/format.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <boost/type_traits.hpp>
#include <lua.hpp>
#if defined(_MSC_VER) && _MSC_VER < 1900
# include "misc/exception.hpp"
#endif
#ifdef __GNUC__
# define ATTR_UNUSED __attribute__((unused))
#else
# define ATTR_UNUSED
#endif
#define LUACONTEXT_GLOBAL_EQ "e5ddced079fc405aa4937b386ca387d2"
#define EQ_FUNCTION_NAME "__eq"
#define TOSTRING_FUNCTION_NAME "__tostring"
/**
* Defines a Lua context
* A Lua context is used to interpret Lua code. Since everything in Lua is a variable (including functions),
* we only provide few functions like readVariable and writeVariable.
*
* You can also write variables with C++ functions so that they are callable by Lua. Note however that you HAVE TO convert
* your function to std::function (not directly std::bind or a lambda function) so the class can detect which argument types
* it wants. These arguments may only be of basic types (int, float, etc.) or std::string.
*/
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
class LuaContext {
struct ValueInRegistry;
template<typename TFunctionObject, typename TFirstParamType> struct Binder;
template<typename T> struct IsOptional;
enum Globals_t { Globals }; // tag for "global variables"
public:
/**
* @param openDefaultLibs True if luaL_openlibs should be called
*/
explicit LuaContext(bool openDefaultLibs = true)
{
// luaL_newstate can return null if allocation failed
mState = luaL_newstate();
if (mState == nullptr)
throw std::bad_alloc();
// setting the panic function
lua_atpanic(mState, [](lua_State* state) -> int {
const std::string str = lua_tostring(state, -1);
lua_pop(state, 1);
assert(false && "lua_atpanic triggered");
exit(0);
});
// opening default library if required to do so
if (openDefaultLibs)
luaL_openlibs(mState);
writeGlobalEq();
}
void writeGlobalEq() {
const auto eqFunction = [](lua_State* lua) -> int {
try {
lua_pushstring(lua, "__eq");
lua_gettable(lua, -2);
/* if not found, return false */
if (lua_isnil(lua, -1)) {
lua_pop(lua, -2);
lua_pushboolean(lua, false);
return 1;
}
lua_insert(lua, lua_gettop(lua)-2);
return callRaw(lua, PushedObject{lua, 3}, 1).release();
} catch(...) {
Pusher<std::exception_ptr>::push(lua, std::current_exception()).release();
luaError(lua);
}
};
lua_pushcfunction(mState, eqFunction);
lua_setglobal(mState, LUACONTEXT_GLOBAL_EQ);
};
/**
* Move constructor
*/
LuaContext(LuaContext&& s) :
mState(s.mState)
{
s.mState = luaL_newstate();
}
/**
* Move operator
*/
LuaContext& operator=(LuaContext&& s) noexcept
{
std::swap(mState, s.mState);
return *this;
}
/**
* Copy is forbidden
*/
LuaContext(const LuaContext&) = delete;
/**
* Copy is forbidden
*/
LuaContext& operator=(const LuaContext&) = delete;
/**
* Destructor
*/
~LuaContext() noexcept
{
assert(mState);
lua_close(mState);
}
/**
* Thrown when an error happens during execution of lua code (like not enough parameters for a function)
*/
class ExecutionErrorException : public std::runtime_error
{
public:
ExecutionErrorException(const std::string& msg) :
std::runtime_error(msg)
{
}
};
/**
* Thrown when a syntax error happens in a lua script
*/
class SyntaxErrorException : public std::runtime_error
{
public:
SyntaxErrorException(const std::string& msg) :
std::runtime_error(msg)
{
}
};
/**
* Thrown when trying to cast a Lua variable to an unvalid type, eg. trying to read a number when the variable is a string
*/
class WrongTypeException : public std::runtime_error
{
public:
WrongTypeException(std::string luaType_, const std::type_info& destination_) :
std::runtime_error("Trying to cast a lua variable from \"" + luaType_ + "\" to \"" + destination_.name() + "\""),
luaType(luaType_),
destination(destination_)
{
}
std::string luaType;
const std::type_info& destination;
};
/**
* Function object that can call a function stored by Lua
* This type is copiable and movable, but not constructible. It can only be created through readVariable.
* @tparam TFunctionType Function type (eg. "int (int, bool)")
*/
template<typename TFunctionType>
class LuaFunctionCaller;
/**
* Opaque type that identifies a Lua object
*/
struct LuaObject {
LuaObject() = default;
LuaObject(lua_State* state, int index=-1) {
this->objectInRegistry = std::make_shared<LuaContext::ValueInRegistry>(state, index);
}
std::shared_ptr<LuaContext::ValueInRegistry> objectInRegistry;
};
/**
* Opaque type that identifies a Lua thread
*/
struct ThreadID {
ThreadID() = default;
ThreadID(ThreadID&& o) : state(o.state), threadInRegistry(std::move(o.threadInRegistry)) { }
ThreadID& operator=(ThreadID&& o) { std::swap(state, o.state); std::swap(threadInRegistry, o.threadInRegistry); return *this; }
public:
friend LuaContext;
lua_State* state;
std::unique_ptr<ValueInRegistry> threadInRegistry;
};
/**
* Type that is considered as an empty array
*/
enum EmptyArray_t { EmptyArray };
/**
* Type for a metatable
*/
enum Metatable_t { Metatable };
/**
* Executes lua code from the stream
* @param code A stream that Lua will read its code from
*/
void executeCode(std::istream& code)
{
auto toCall = load(mState, code);
call<std::tuple<>>(mState, std::move(toCall));
}
/**
* Executes lua code from the stream and returns a value
* @param code A stream that Lua will read its code from
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(std::istream& code)
-> TType
{
auto toCall = load(mState, code);
return call<TType>(mState, std::move(toCall));
}
/**
* Executes lua code given as parameter
* @param code A string containing code that will be executed by Lua
*/
void executeCode(const std::string& code)
{
executeCode(code.c_str());
}
/*
* Executes Lua code from the stream and returns a value
* @param code A string containing code that will be executed by Lua
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(const std::string& code)
-> TType
{
return executeCode<TType>(code.c_str());
}
/**
* Executes Lua code
* @param code A string containing code that will be executed by Lua
*/
void executeCode(const char* code)
{
auto toCall = load(mState, code);
call<std::tuple<>>(mState, std::move(toCall));
}
/*
* Executes Lua code from the stream and returns a value
* @param code A string containing code that will be executed by Lua
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(const char* code)
-> TType
{
auto toCall = load(mState, code);
return call<TType>(mState, std::move(toCall));
}
/**
* Executes lua code from the stream
* @param code A stream that Lua will read its code from
*/
void executeCode(const ThreadID& thread, std::istream& code)
{
auto toCall = load(thread.state, code);
call<std::tuple<>>(thread.state, std::move(toCall));
}
/**
* Executes lua code from the stream and returns a value
* @param code A stream that Lua will read its code from
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(const ThreadID& thread, std::istream& code)
-> TType
{
auto toCall = load(thread.state, code);
return call<TType>(thread.state, std::move(toCall));
}
/**
* Executes lua code given as parameter
* @param code A string containing code that will be executed by Lua
*/
void executeCode(const ThreadID& thread, const std::string& code)
{
executeCode(thread, code.c_str());
}
/*
* Executes Lua code from the stream and returns a value
* @param code A string containing code that will be executed by Lua
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(const ThreadID& thread, const std::string& code)
-> TType
{
return executeCode<TType>(thread, code.c_str());
}
/**
* Executes Lua code
* @param code A string containing code that will be executed by Lua
*/
void executeCode(const ThreadID& thread, const char* code)
{
auto toCall = load(thread.state, code);
call<std::tuple<>>(thread.state, std::move(toCall));
}
/*
* Executes Lua code from the stream and returns a value
* @param code A string containing code that will be executed by Lua
* @tparam TType The type that the executing code should return
*/
template<typename TType>
auto executeCode(const ThreadID& thread, const char* code)
-> TType
{
auto toCall = load(thread.state, code);
return call<TType>(thread.state, std::move(toCall));
}
/**
* Tells that Lua will be allowed to access an object's function
* This is the version "registerFunction(name, &Foo::function)"
*/
template<typename TPointerToMemberFunction>
auto registerFunction(const std::string& name, TPointerToMemberFunction pointer)
-> typename std::enable_if<std::is_member_function_pointer<TPointerToMemberFunction>::value>::type
{
registerFunctionImpl(name, std::mem_fn(pointer), tag<TPointerToMemberFunction>{});
}
/**
* Tells that Lua will be allowed to access an object's function
* This is the version with an explicit template parameter: "registerFunction<void (Foo::*)()>(name, [](Foo&) { })"
* @param fn Function object which takes as first parameter a reference to the object
* @tparam TFunctionType Pointer-to-member function type
*/
template<typename TFunctionType, typename TType>
void registerFunction(const std::string& functionName, TType fn)
{
static_assert(std::is_member_function_pointer<TFunctionType>::value, "registerFunction must take a member function pointer type as template parameter");
registerFunctionImpl(functionName, std::move(fn), tag<TFunctionType>{});
}
/**
* Tells that Lua will be allowed to access an object's function
* This is the alternative version with an explicit template parameter: "registerFunction<Foo, void (*)()>(name, [](Foo&) { })"
* @param fn Function object which takes as first parameter a reference to the object
* @tparam TObject Object to register this function to
* @tparam TFunctionType Function type
*/
template<typename TObject, typename TFunctionType, typename TType>
void registerFunction(const std::string& functionName, TType fn)
{
static_assert(std::is_function<TFunctionType>::value, "registerFunction must take a function type as template parameter");
registerFunctionImpl(functionName, std::move(fn), tag<TObject>{}, tag<TFunctionType>{});
}
/**
* Wrappers for registering "__eq" function in case we want to change this to something else some day
*/
template<typename TPointerToMemberFunction>
auto registerEqFunction(TPointerToMemberFunction pointer)
-> typename std::enable_if<std::is_member_function_pointer<TPointerToMemberFunction>::value>::type
{
registerFunctionImpl(EQ_FUNCTION_NAME, std::mem_fn(pointer), tag<TPointerToMemberFunction>{});
}
template<typename TFunctionType, typename TType>
void registerEqFunction(TType fn)
{
static_assert(std::is_member_function_pointer<TFunctionType>::value, "registerFunction must take a member function pointer type as template parameter");
registerFunctionImpl(EQ_FUNCTION_NAME, std::move(fn), tag<TFunctionType>{});
}
template<typename TObject, typename TFunctionType, typename TType>
void registerEqFunction(TType fn)
{
static_assert(std::is_function<TFunctionType>::value, "registerFunction must take a function type as template parameter");
registerFunctionImpl(EQ_FUNCTION_NAME, std::move(fn), tag<TObject>{}, tag<TFunctionType>{});
}
/**
* Wrappers for registering "__tostring" function in case we want to change this to something else some day
*/
template<typename TPointerToMemberFunction>
auto registerToStringFunction(TPointerToMemberFunction pointer)
-> typename std::enable_if<std::is_member_function_pointer<TPointerToMemberFunction>::value>::type
{
registerFunctionImpl(TOSTRING_FUNCTION_NAME, std::mem_fn(pointer), tag<TPointerToMemberFunction>{});
}
template<typename TFunctionType, typename TType>
void registerToStringFunction(TType fn)
{
static_assert(std::is_member_function_pointer<TFunctionType>::value, "registerFunction must take a member function pointer type as template parameter");
registerFunctionImpl(TOSTRING_FUNCTION_NAME, std::move(fn), tag<TFunctionType>{});
}
template<typename TObject, typename TFunctionType, typename TType>
void registerToStringFunction(TType fn)
{
static_assert(std::is_function<TFunctionType>::value, "registerFunction must take a function type as template parameter");
registerFunctionImpl(TOSTRING_FUNCTION_NAME, std::move(fn), tag<TObject>{}, tag<TFunctionType>{});
}
/**
* Inverse operation of registerFunction
* @tparam TType Type whose function belongs to
*/
template<typename TType>
void unregisterFunction(const std::string& /*functionName*/)
{
lua_pushlightuserdata(mState, const_cast<std::type_info*>(&typeid(TType)));
lua_pushnil(mState);
lua_settable(mState, LUA_REGISTRYINDEX);
checkTypeRegistration(mState, &typeid(TType));
lua_pushlightuserdata(mState, const_cast<std::type_info*>(&typeid(TType*)));
lua_pushnil(mState);
lua_settable(mState, LUA_REGISTRYINDEX);
checkTypeRegistration(mState, &typeid(TType*));
lua_pushlightuserdata(mState, const_cast<std::type_info*>(&typeid(std::shared_ptr<TType>)));
lua_pushnil(mState);
lua_settable(mState, LUA_REGISTRYINDEX);
checkTypeRegistration(mState, &typeid(std::shared_ptr<TType>));
}
/**
* Registers a member variable
* This is the version "registerMember(name, &Foo::member)"
*/
template<typename TObject, typename TVarType>
void registerMember(const std::string& name, TVarType TObject::*member)
{
// implementation simply calls the custom member with getter and setter
const auto getter = [=](const TObject& obj) -> TVarType { return obj.*member; };
const auto setter = [=](TObject& obj, const TVarType& value) { obj.*member = value; };
registerMember<TVarType (TObject::*)>(name, getter, setter);
}
/**
* Registers a member variable
* This is the version "registerMember<Foo, int>(name, getter, setter)"
* @tparam TObject Type to register the member to
* @tparam TVarType Type of the member
* @param name Name of the member to register
* @param readFunction Function of type "TVarType (const TObject&)"
* @param writeFunction_ Function of type "void (TObject&, const TVarType&)"
*/
template<typename TObject, typename TVarType, typename TReadFunction, typename TWriteFunction>
void registerMember(const std::string& name, TReadFunction readFunction, TWriteFunction writeFunction_)
{
registerMemberImpl<TObject,TVarType>(name, std::move(readFunction), std::move(writeFunction_));
}
/**
* Registers a member variable
* This is the version "registerMember<int (Foo::*)>(name, getter, setter)"
* @tparam TMemberType Pointer to member object representing the type
* @param name Name of the member to register
* @param readFunction Function of type "TVarType (const TObject&)"
* @param writeFunction_ Function of type "void (TObject&, const TVarType&)"
*/
template<typename TMemberType, typename TReadFunction, typename TWriteFunction>
void registerMember(const std::string& name, TReadFunction readFunction, TWriteFunction writeFunction_)
{
static_assert(std::is_member_object_pointer<TMemberType>::value, "registerMember must take a member object pointer type as template parameter");
registerMemberImpl(tag<TMemberType>{}, name, std::move(readFunction), std::move(writeFunction_));
}
/**
* Registers a non-modifiable member variable
* This is the version "registerMember<Foo, int>(name, getter)"
* @tparam TObject Type to register the member to
* @tparam TVarType Type of the member
* @param name Name of the member to register
* @param readFunction Function of type "TVarType (const TObject&)"
*/
template<typename TObject, typename TVarType, typename TReadFunction>
void registerMember(const std::string& name, TReadFunction readFunction)
{
registerMemberImpl<TObject,TVarType>(name, std::move(readFunction));
}
/**
* Registers a non-modifiable member variable
* This is the version "registerMember<int (Foo::*)>(name, getter)"
* @tparam TMemberType Pointer to member object representing the type
* @param name Name of the member to register
* @param readFunction Function of type "TVarType (const TObject&)"
*/
template<typename TMemberType, typename TReadFunction>
void registerMember(const std::string& name, TReadFunction readFunction)
{
static_assert(std::is_member_object_pointer<TMemberType>::value, "registerMember must take a member object pointer type as template parameter");
registerMemberImpl(tag<TMemberType>{}, name, std::move(readFunction));
}
/**
* Registers a dynamic member variable
* This is the version "registerMember<Foo, int>(getter, setter)"
* @tparam TObject Type to register the member to
* @tparam TVarType Type of the member
* @param readFunction Function of type "TVarType (const TObject&, const std::string&)"
* @param writeFunction_ Function of type "void (TObject&, const std::string&, const TVarType&)"
*/
template<typename TObject, typename TVarType, typename TReadFunction, typename TWriteFunction>
void registerMember(TReadFunction readFunction, TWriteFunction writeFunction_)
{
registerMemberImpl<TObject,TVarType>(std::move(readFunction), std::move(writeFunction_));
}
/**
* Registers a dynamic member variable
* This is the version "registerMember<int (Foo::*)>(getter, setter)"
* @tparam TMemberType Pointer to member object representing the type
* @param readFunction Function of type "TVarType (const TObject&, const std::string&)"
* @param writeFunction_ Function of type "void (TObject&, const std::string&, const TVarType&)"
*/
template<typename TMemberType, typename TReadFunction, typename TWriteFunction>
void registerMember(TReadFunction readFunction, TWriteFunction writeFunction_)
{
static_assert(std::is_member_object_pointer<TMemberType>::value, "registerMember must take a member object pointer type as template parameter");
registerMemberImpl(tag<TMemberType>{}, std::move(readFunction), std::move(writeFunction_));
}
/**
* Registers a dynamic non-modifiable member variable
* This is the version "registerMember<Foo, int>(getter)"
* @tparam TObject Type to register the member to
* @tparam TVarType Type of the member
* @param readFunction Function of type "TVarType (const TObject&, const std::string&)"
*/
template<typename TObject, typename TVarType, typename TReadFunction>
void registerMember(TReadFunction readFunction)
{
registerMemberImpl<TObject, TVarType>(std::move(readFunction));
}
/**
* Registers a dynamic non-modifiable member variable
* This is the version "registerMember<int (Foo::*)>(getter)"
* @tparam TMemberType Pointer to member object representing the type
* @param readFunction Function of type "TVarType (const TObject&, const std::string&)"
*/
template<typename TMemberType, typename TReadFunction>
void registerMember(TReadFunction readFunction)
{
static_assert(std::is_member_object_pointer<TMemberType>::value, "registerMember must take a member object pointer type as template parameter");
registerMemberImpl(tag<TMemberType>{}, std::move(readFunction));
}
/**
* Creates a new thread
* A Lua thread is not really a thread, but rather an "execution stack".
* You can destroy the thread by calling destroyThread
* @sa destroyThread
*/
auto createThread()
-> ThreadID
{
ThreadID result;
result.state = lua_newthread(mState);
result.threadInRegistry = std::unique_ptr<ValueInRegistry>(new ValueInRegistry(mState));
lua_pop(mState, 1);
return result;
}
/**
* Destroys a thread created with createThread
* @sa createThread
*/
void destroyThread(ThreadID& id)
{
id.threadInRegistry.reset();
}
/**
* Reads the content of a Lua variable
*
* @tparam TType Type requested for the read
* @throw WrongTypeException When the variable is not convertible to the requested type
* @sa writeVariable
*
* Readable types are all types accepted by writeVariable except nullptr, std::unique_ptr and function pointers
* Additionally supported:
* - LuaFunctionCaller<FunctionType>, which is an alternative to std::function
* - references to custom objects, in which case it will return the object in-place
*
* After the variable name, you can add other parameters.
* If the variable is an array, it will instead get the element of that array whose offset is the second parameter.
* Same applies for third, fourth, etc. parameters.
*/
template<typename TType, typename... TTypes>
TType readVariable(const std::string& name, TTypes&&... elements) const
{
lua_getglobal(mState, name.c_str());
lookIntoStackTop(mState, std::forward<TTypes>(elements)...);
return readTopAndPop<TType>(mState, PushedObject{mState, 1});
}
/**
* @sa readVariable
*/
template<typename TType, typename... TTypes>
TType readVariable(const char* name, TTypes&&... elements) const
{
lua_getglobal(mState, name);
lookIntoStackTop(mState, std::forward<TTypes>(elements)...);
return readTopAndPop<TType>(mState, PushedObject{mState, 1});
}
/**
* @sa readVariable
*/
template<typename TType, typename... TTypes>
TType readVariable(const ThreadID& thread, const std::string& name, TTypes&&... elements) const
{
lua_getglobal(thread.state, name.c_str());
lookIntoStackTop(thread.state, std::forward<TTypes>(elements)...);
return readTopAndPop<TType>(thread.state, PushedObject{thread.state, 1});
}
/**
* @sa readVariable
*/
template<typename TType, typename... TTypes>
TType readVariable(const ThreadID& thread, const char* name, TTypes&&... elements) const
{
lua_getglobal(thread.state, name);
lookIntoStackTop(thread.state, std::forward<TTypes>(elements)...);
return readTopAndPop<TType>(thread.state, PushedObject{thread.state, 1});
}
/**
* Changes the content of a Lua variable
*
* Accepted values are:
* - all base types (char, short, int, float, double, bool)
* - std::string
* - enums
* - std::vector<>
* - std::vector<std::pair<>>, std::map<> and std::unordered_map<> (the key and value must also be accepted values)
* - std::function<> (all parameters must be accepted values, and return type must be either an accepted value for readVariable or a tuple)
* - std::shared_ptr<> (std::unique_ptr<> are converted to std::shared_ptr<>)
* - nullptr (writes nil)
* - any object
*
* All objects are passed by copy and destroyed by the garbage collector if necessary.
*/
template<typename... TData>
void writeVariable(TData&&... data) noexcept {
static_assert(sizeof...(TData) >= 2, "You must pass at least a variable name and a value to writeVariable");
typedef typename std::decay<typename std::tuple_element<sizeof...(TData) - 1,std::tuple<TData...>>::type>::type
RealDataType;
static_assert(!std::is_same<typename Tupleizer<RealDataType>::type,RealDataType>::value, "Error: you can't use LuaContext::writeVariable with a tuple");
setTable<RealDataType>(mState, Globals, std::forward<TData>(data)...);
}
/**
* Equivalent to writeVariable(varName, ..., std::function<TFunctionType>(data));
* This version is more efficient than writeVariable if you want to write functions
*/
template<typename TFunctionType, typename... TData>
void writeFunction(TData&&... data) noexcept {
static_assert(sizeof...(TData) >= 2, "You must pass at least a variable name and a value to writeFunction");
setTable<TFunctionType>(mState, Globals, std::forward<TData>(data)...);
}
/**
* Same as the other writeFunction, except that the template parameter is automatically detected
* This only works if the data is either a native function pointer, or contains one operator() (this is the case for lambdas)
*/
template<typename... TData>
void writeFunction(TData&&... data) noexcept {
static_assert(sizeof...(TData) >= 2, "You must pass at least a variable name and a value to writeFunction");
typedef typename std::decay<typename std::tuple_element<sizeof...(TData) - 1,std::tuple<TData...>>::type>::type
RealDataType;
typedef typename FunctionTypeDetector<RealDataType>::type
DetectedFunctionType;
return writeFunction<DetectedFunctionType>(std::forward<TData>(data)...);
}
private:
// the state is the most important variable in the class since it is our interface with Lua
// - registered members and functions are stored in tables at offset &typeid(type) of the registry
// each table has its getter functions at offset 0, getter members at offset 1, default getter at offset 2
// offset 3 is unused, setter members at offset 4, default setter at offset 5
lua_State* mState;
/**************************************************/
/* PUSH OBJECT */
/**************************************************/
struct PushedObject {
PushedObject(lua_State* state_, int num_ = 1) : state(state_), num(num_) {}
~PushedObject() { assert(lua_gettop(state) >= num); if (num >= 1) lua_pop(state, num); }
PushedObject& operator=(const PushedObject&) = delete;
PushedObject(const PushedObject&) = delete;
PushedObject& operator=(PushedObject&& other) { std::swap(state, other.state); std::swap(num, other.num); return *this; }
PushedObject(PushedObject&& other) : state(other.state), num(other.num) { other.num = 0; }
PushedObject operator+(PushedObject&& other) && { PushedObject obj(state, num + other.num); num = 0; other.num = 0; return obj; }
void operator+=(PushedObject&& other) { assert(state == other.state); num += other.num; other.num = 0; }
auto getState() const -> lua_State* { return state; }
auto getNum() const -> int { return num; }
int release() { const auto n = num; num = 0; return n; }
void pop() { if (num >= 1) lua_pop(state, num); num = 0; }
void pop(int n) { assert(num >= n); lua_pop(state, n); num -= n; }
private:
lua_State* state;
int num = 0;
};
/**************************************************/
/* MISC */
/**************************************************/
// type used as a tag
template<typename T>
struct tag {};
// tag for "the registry"
enum RegistryTag { Registry };
// this function takes a value representing the offset to look into
// it will look into the top element of the stack and replace the element by its content at the given index
template<typename OffsetType1, typename... OffsetTypeOthers>
static void lookIntoStackTop(lua_State* state, OffsetType1&& offset1, OffsetTypeOthers&&... offsetOthers) {
static_assert(Pusher<typename std::decay<OffsetType1>::type>::minSize == 1 && Pusher<typename std::decay<OffsetType1>::type>::maxSize == 1, "Impossible to have a multiple-values index");
auto p1 = Pusher<typename std::decay<OffsetType1>::type>::push(state, offset1);
lua_gettable(state, -2);
lua_remove(state, -2);
p1.release();
lookIntoStackTop(state, std::forward<OffsetTypeOthers>(offsetOthers)...);
}
template<typename... OffsetTypeOthers>
static void lookIntoStackTop(lua_State* state, Metatable_t, OffsetTypeOthers&&... offsetOthers) {
lua_getmetatable(state, -1);
lua_remove(state, -2);
lookIntoStackTop(state, std::forward<OffsetTypeOthers>(offsetOthers)...);
}
static void lookIntoStackTop(lua_State*) {
}
// equivalent of lua_settable with t[k]=n, where t is the value at the index in the template parameter, k is the second parameter, n is the last parameter, and n is pushed by the function in the first parameter
// if there are more than 3 parameters, parameters 3 to n-1 are considered as sub-indices into the array
// the dataPusher MUST push only one thing on the stack
// TTableIndex must be either LUA_REGISTRYINDEX, LUA_GLOBALSINDEX, LUA_ENVINDEX, or the position of the element on the stack
template<typename TDataType, typename TIndex, typename TData>
static void setTable(lua_State* state, const PushedObject&, TIndex&& index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TIndex>::type>::minSize == 1 && Pusher<typename std::decay<TIndex>::type>::maxSize == 1, "Impossible to have a multiple-values index");
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TIndex>::type>::push(state, index);
auto p2 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_settable(state, -3);
p1.release();
p2.release();
}
template<typename TDataType, typename TData>
static void setTable(lua_State* state, const PushedObject&, const std::string& index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_setfield(state, -2, index.c_str());
p1.release();
}
template<typename TDataType, typename TData>
static void setTable(lua_State* state, const PushedObject&, const char* index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_setfield(state, -2, index);
p1.release();
}
template<typename TDataType, typename TData>
static void setTable(lua_State* state, const PushedObject&, Metatable_t, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_setmetatable(state, -2);
p1.release();
}
template<typename TDataType, typename TIndex1, typename TIndex2, typename TIndex3, typename... TIndices>
static auto setTable(lua_State* state, PushedObject&, TIndex1&& index1, TIndex2&& index2, TIndex3&& index3, TIndices&&... indices) noexcept
-> typename std::enable_if<!std::is_same<typename std::decay<TIndex1>::type, Metatable_t>::value>::type
{
static_assert(Pusher<typename std::decay<TIndex1>::type>::minSize == 1 && Pusher<typename std::decay<TIndex1>::type>::maxSize == 1, "Impossible to have a multiple-values index");
auto p1 = Pusher<typename std::decay<TIndex1>::type>::push(state, std::forward<TIndex1>(index1));
lua_gettable(state, -2);
setTable<TDataType>(state, std::move(p1), std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
}
template<typename TDataType, typename TIndex1, typename TIndex2, typename TIndex3, typename... TIndices>
static auto setTable(lua_State* state, PushedObject&& pushedTable, TIndex1&& index1, TIndex2&& index2, TIndex3&& index3, TIndices&&... indices) noexcept
-> typename std::enable_if<!std::is_same<typename std::decay<TIndex1>::type, Metatable_t>::value>::type
{
static_assert(Pusher<typename std::decay<TIndex1>::type>::minSize == 1 && Pusher<typename std::decay<TIndex1>::type>::maxSize == 1, "Impossible to have a multiple-values index");
auto p1 = Pusher<typename std::decay<TIndex1>::type>::push(state, std::forward<TIndex1>(index1)) + std::move(pushedTable);
lua_gettable(state, -2);
setTable<TDataType>(state, std::move(p1), std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
}
template<typename TDataType, typename TIndex2, typename TIndex3, typename... TIndices>
static void setTable(lua_State* state, PushedObject& pushedObject, Metatable_t, TIndex2&& index2, TIndex3&& index3, TIndices&&... indices) noexcept
{
if (lua_getmetatable(state, -1) == 0)
{
lua_newtable(state);
PushedObject p1{state, 1};
setTable<TDataType>(state, p1, std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
lua_setmetatable(state, -2);
p1.release();
}
else
{
setTable<TDataType>(state, pushedObject, std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
}
}
template<typename TDataType, typename TIndex2, typename TIndex3, typename... TIndices>
static void setTable(lua_State* state, PushedObject&& pushedObject, Metatable_t, TIndex2&& index2, TIndex3&& index3, TIndices&&... indices) noexcept
{
if (lua_getmetatable(state, -1) == 0)
{
lua_newtable(state);
PushedObject p1{state, 1};
setTable<TDataType>(state, p1, std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
lua_setmetatable(state, -2);
p1.release();
}
else
{
setTable<TDataType>(state, std::move(pushedObject), std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
}
}
template<typename TDataType, typename TIndex, typename TData>
static void setTable(lua_State* state, RegistryTag, TIndex&& index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TIndex>::type>::minSize == 1 && Pusher<typename std::decay<TIndex>::type>::maxSize == 1, "Impossible to have a multiple-values index");
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TIndex>::type>::push(state, index);
auto p2 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_settable(state, LUA_REGISTRYINDEX);
p1.release();
p2.release();
}
template<typename TDataType, typename TData>
static void setTable(lua_State* state, RegistryTag, const std::string& index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_setfield(state, LUA_REGISTRYINDEX, index.c_str());
p1.release();
}
template<typename TDataType, typename TData>
static void setTable(lua_State* state, RegistryTag, const char* index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
auto p1 = Pusher<typename std::decay<TDataType>::type>::push(state, std::forward<TData>(data));
lua_setfield(state, LUA_REGISTRYINDEX, index);
p1.release();
}
template<typename TDataType, typename TIndex1, typename TIndex2, typename TIndex3, typename... TIndices>
static void setTable(lua_State* state, RegistryTag, TIndex1&& index1, TIndex2&& index2, TIndex3&& index3, TIndices&&... indices) noexcept
{
static_assert(Pusher<typename std::decay<TIndex1>::type>::minSize == 1 && Pusher<typename std::decay<TIndex1>::type>::maxSize == 1, "Impossible to have a multiple-values index");
auto p1 = Pusher<typename std::decay<TIndex1>::type>::push(state, std::forward<TIndex1>(index1));
lua_gettable(state, LUA_REGISTRYINDEX);
setTable<TDataType>(state, std::move(p1), std::forward<TIndex2>(index2), std::forward<TIndex3>(index3), std::forward<TIndices>(indices)...);
}
template<typename TDataType, typename TIndex, typename TData>
static void setTable(lua_State* state, Globals_t, TIndex&& index, TData&& data) noexcept
{
static_assert(Pusher<typename std::decay<TIndex>::type>::minSize == 1 && Pusher<typename std::decay<TIndex>::type>::maxSize == 1, "Impossible to have a multiple-values index");
static_assert(Pusher<typename std::decay<TDataType>::type>::minSize == 1 && Pusher<typename std::decay<TDataType>::type>::maxSize == 1, "Impossible to have a multiple-values data");
# if LUA_VERSION_NUM >= 502