-
Notifications
You must be signed in to change notification settings - Fork 4
/
state.d
1393 lines (1207 loc) · 38 KB
/
state.d
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
module lumars.state;
import bindbc.lua, taggedalgebraic, lumars;
import taggedalgebraic : visit;
import std.typecons : Nullable, isTuple;
import std.traits : hasUDA, FieldNameTuple;
import std.meta : AliasSeq;
struct ShowInLua {}
struct HideFromLua {}
template FieldIndex(T, string fieldName)
{
enum FieldIndex = fieldIndexImpl!(T, fieldName, 0);
}
private template fieldIndexImpl(T, string fieldName, int i)
{
static if (T.tupleof.length <= i)
{
static assert(false, "The given field \"" ~ fieldName ~ "\" doesn't exist in the type \"" ~ T.stringof ~ "\"");
enum fieldIndexImpl = -1;
}
else static if (__traits(identifier, T.tupleof[i]) == fieldName)
{
enum fieldIndexImpl = i;
}
else
{
enum fieldIndexImpl = fieldIndexImpl!(T, fieldName, i + 1);
}
}
template FieldType(T, string fieldName, int i = 0)
{
static if (isTuple!T)
alias FieldType = TupleFieldType!(T, fieldName, 0);
else
alias FieldType = StructFieldType!(T, fieldName, 0);
}
template TupleFieldType(T, string fieldName, int i)
{
static if (T.Types.length <= i)
{
static assert(false, "The given field \"" ~ fieldName ~ "\" doesn't exist in the type \"" ~ T.stringof ~ "\"");
}
else static if (T.fieldNames[i] == fieldName)
{
alias TupleFieldType = T.Types[i];
}
else
{
alias TupleFieldType = TupleFieldType!(T, fieldName, i + 1);
}
}
template StructFieldType(T, string fieldName, int i)
{
static if (T.tupleof.length <= i)
{
static assert(false, "The given field \"" ~ fieldName ~ "\" doesn't exist in the type \"" ~ T.stringof ~ "\"");
}
else static if (__traits(identifier, T.tupleof[i]) == fieldName)
{
alias StructFieldType = typeof(T.tupleof[i]);
}
else
{
alias StructFieldType = StructFieldType!(T, fieldName, i + 1);
}
}
private auto getFieldValue(string fieldName, T)(T obj)
{
static if (isTuple!T)
return mixin("obj." ~ fieldName);
else
return obj.tupleof[FieldIndex!(T, fieldName)];
}
private void setFieldValue(string fieldName, T, U)(ref T obj, U value)
{
static if (isTuple!T)
mixin("obj." ~ fieldName ~ " = value;");
else
obj.tupleof[FieldIndex!(T, fieldName)] = value;
}
template isVisibleField(T, string fieldName)
{
enum i = FieldIndex!(T, fieldName);
enum isVisibleField = !hasUDA!(T.tupleof[i], HideFromLua) && (
hasUDA!(T.tupleof[i], ShowInLua) ||
__traits(getVisibility, T.tupleof[i]) == "public" ||
__traits(getVisibility, T.tupleof[i]) == "export"
);
}
template VisibleFieldNameTuple(T)
{
alias VisibleFieldNameTuple = AliasSeq!();
static if (isTuple!T)
{
VisibleFieldNameTuple = T.fieldNames;
}
else
{
static foreach (member; FieldNameTuple!T)
static if (isVisibleField!(T, member))
VisibleFieldNameTuple = AliasSeq!(VisibleFieldNameTuple, member);
}
}
unittest
{
struct S
{
int a;
@HideFromLua int b;
private int c;
@ShowInLua private int d;
export int e;
protected int f;
}
static assert(isVisibleField!(S, "a"));
static assert(!isVisibleField!(S, "b"));
static assert(!isVisibleField!(S, "c"));
static assert(isVisibleField!(S, "d"));
static assert(isVisibleField!(S, "e"));
static assert(!isVisibleField!(S, "f"));
alias vfnt = VisibleFieldNameTuple!S;
static assert(vfnt == AliasSeq!("a", "d", "e"));
import std.typecons : Tuple;
alias T = Tuple!(int, "a", int, "b");
T t;
static assert(isVisibleField!(S, "a"));
static assert(!isVisibleField!(S, "b"));
alias vfnt2 = VisibleFieldNameTuple!T;
static assert(vfnt2 == AliasSeq!("a", "b"));
}
/// Used to represent LUA's `nil`.
struct LuaNil {}
/// See `LuaValue`
union LuaValueUnion
{
/// LUA `nil`
LuaNil nil;
/// A lua number
lua_Number number;
/// A weak reference to some text. This text is managed by LUA and not D's GC so is unsafe to escape
const(char)[] textWeak;
/// GC-managed text
string text;
/// A bool
bool boolean;
/// A weak reference to a table currently on the LUA stack.
LuaTableWeak tableWeak;
/// A strong reference to a table which is in the LUA registry.
LuaTable table;
/// A weak reference to a function currently on the LUA stack.
LuaFuncWeak funcWeak;
/// A strong reference to a function which is in the LUA registry.
LuaFunc func;
void* userData;
}
/// An enumeration of various status codes LUA may return.
enum LuaStatus
{
ok = 0,
yield = LUA_YIELD,
errRun = LUA_ERRRUN,
errSyntax = LUA_ERRSYNTAX,
errMem = LUA_ERRMEM,
errErr = LUA_ERRERR,
}
/// A `TaggedUnion` of `LuaValueUnion` which is used to bridge the gap between D and Lua values.
alias LuaValue = TaggedUnion!LuaValueUnion;
alias LuaNumber = lua_Number;
alias LuaCFunc = lua_CFunction;
/++
+ A light wrapper around `lua_State` with some higher level functions for quality of life purposes.
+
+ This struct cannot be copied, so put it on the heap or store it as a global.
+ ++/
struct LuaState
{
import std.string : toStringz;
import std.stdio : writefln, writeln, writef;
@disable this(this){}
private
{
lua_State* _handle;
LuaTablePseudo _G;
}
package bool _isWrapper;
/// Creates a wrapper around the given `lua_state`, or creates a new state if the given value is null.
@trusted
this(lua_State* wrapAround)
{
if(wrapAround)
{
this._handle = wrapAround;
this._isWrapper = true;
}
else
{
loadLuaIfNeeded();
this._handle = luaL_newstate();
luaL_openlibs(this.handle);
}
this._G = LuaTablePseudo(&this, LUA_GLOBALSINDEX);
}
/// For non-wrappers, destroy the lua state.
@trusted @nogc
~this() nothrow
{
if(this._handle && !this._isWrapper)
lua_close(this._handle);
}
@nogc
LuaTablePseudo globalTable() nothrow
{
return this._G;
}
@nogc
lua_CFunction atPanic(lua_CFunction func) nothrow
{
return lua_atpanic(this.handle, func);
}
@nogc
void call(int nargs, int nresults) nothrow
{
lua_call(this.handle, nargs, nresults);
}
@nogc
bool checkStack(int amount) nothrow
{
return lua_checkstack(this.handle, amount) != 0;
}
@nogc
void concat(int nargs) nothrow
{
lua_concat(this.handle, nargs);
}
@nogc
bool equal(int index1, int index2) nothrow
{
return lua_equal(this.handle, index1, index2) != 0;
}
@nogc
void error() nothrow
{
lua_error(this.handle);
}
void error(const char[] msg) nothrow
{
luaL_error(this.handle, "%s", msg.toStringz);
}
LuaTableWeak pushMetatable(int ofIndex)
{
lua_getmetatable(this.handle, ofIndex);
return LuaTableWeak(&this, -1);
}
LuaTable getMetatable(int ofIndex)
{
lua_getmetatable(this.handle, ofIndex);
return LuaTable.makeRef(&this);
}
@nogc
bool lessThan(int index1, int index2) nothrow
{
return lua_lessthan(this.handle, index1, index2) != 0;
}
@nogc
bool rawEqual(int index1, int index2) nothrow
{
return lua_rawequal(this.handle, index1, index2) != 0;
}
@nogc
void pushTable(int tableIndex) nothrow
{
return lua_gettable(this.handle, tableIndex);
}
@nogc
void insert(int index) nothrow
{
return lua_insert(this.handle, index);
}
@nogc
size_t len(int index) nothrow
{
return lua_objlen(this.handle, index);
}
@nogc
LuaStatus pcall(int nargs, int nresults, int errFuncIndex) nothrow
{
return cast(LuaStatus)lua_pcall(this.handle, nargs, nresults, errFuncIndex);
}
@nogc
void copy(int index) nothrow
{
lua_pushvalue(this.handle, index);
}
@nogc
void rawGet(int tableIndex) nothrow
{
lua_rawget(this.handle, tableIndex);
}
@nogc
void rawGet(int tableIndex, int indexIntoTable) nothrow
{
lua_rawgeti(this.handle, tableIndex, indexIntoTable);
}
@nogc
void rawSet(int tableIndex) nothrow
{
lua_rawset(this.handle, tableIndex);
}
@nogc
void rawSet(int tableIndex, int indexIntoTable) nothrow
{
lua_rawseti(this.handle, tableIndex, indexIntoTable);
}
void getGlobal(const char[] name)
{
lua_getglobal(this.handle, name.toStringz);
}
void setGlobal(const char[] name)
{
lua_setglobal(this.handle, name.toStringz);
}
void register(const char[] name, LuaCFunc func) nothrow
{
lua_register(this.handle, name.toStringz, func);
}
/++
+ Registers the given D function into Lua, under a specific name within the global table.
+
+ `Func` can be any normal D function. By default it is wrapped using `luaCWrapperSmart`
+ to allow a (mostly) seamless way of interfacing D and Lua together. Please see `luaCWrapperSmart`'s
+ documentation if you'd like to learn more.
+
+ Params:
+ Func = The function to wrap.
+ name = The name to register the function under.
+ ++/
void register(alias Func)(const char[] name)
{
this.register(name, &luaCWrapperSmart!Func);
}
/++
+ Similar to the other register functions, except this one will register the functions
+ into a single table, before registering the resulting table into the global table.
+
+ In other words: If you want to make a "library" table then this is the function for you.
+
+ `Args` must have an even number of elements, where each two elements are a pair.
+
+ For each pair in `Args`, the first element is the name to register the function under, and
+ the last element is the function itself to register.
+
+ For example, if you did: `register!("a", (){}, "b", (){})("library")`, then the result is
+ a global table called "library" with the functions "a" and "b" (e.g. `library.a()`).
+ ++/
void register(Args...)(const char[] libname)
if(Args.length % 2 == 0)
{
import std.traits : getUDAs;
luaL_Reg[(Args.length / 2) + 1] reg;
static foreach(i; 0..Args.length/2)
reg[i] = luaL_Reg(Args[i*2].ptr, &luaCWrapperSmart!(Args[i*2+1]));
luaL_register(this.handle, libname.toStringz, reg.ptr);
}
@nogc
void remove(int index) nothrow
{
lua_remove(this.handle, index);
}
@nogc
void replace(int index) nothrow
{
lua_replace(this.handle, index);
}
@nogc
void setMetatable(int ofIndex) nothrow
{
lua_setmetatable(this.handle, ofIndex);
}
void checkArg(bool condition, int argNum, const(char)[] extraMsg = null) nothrow
{
luaL_argcheck(this.handle, condition ? 1 : 0, argNum, extraMsg ? extraMsg.toStringz : null);
}
bool callMetamethod(int index, const char[] method) nothrow
{
return luaL_callmeta(this.handle, index, method.toStringz) != 0;
}
@nogc
void checkAny(int arg) nothrow
{
luaL_checkany(this.handle, arg);
}
@nogc
ptrdiff_t checkInt(int arg) nothrow
{
return luaL_checkinteger(this.handle, arg);
}
@nogc
const(char)[] checkStringWeak(int arg) nothrow
{
size_t len;
const ptr = luaL_checklstring(this.handle, arg, &len);
return ptr[0..len];
}
string checkString(int arg) nothrow
{
return checkStringWeak(arg).idup;
}
@nogc
LuaNumber checkNumber(int arg) nothrow
{
return luaL_checknumber(this.handle, arg);
}
@nogc
void checkType(LuaValue.Kind type, int arg) nothrow
{
int t;
final switch(type) with(LuaValue.Kind)
{
case nil: t = LUA_TNIL; break;
case number: t = LUA_TNUMBER; break;
case textWeak:
case text: t = LUA_TSTRING; break;
case boolean: t = LUA_TBOOLEAN; break;
case tableWeak:
case table: t = LUA_TTABLE; break;
case funcWeak:
case func: t = LUA_TFUNCTION; break;
case userData: t = LUA_TLIGHTUSERDATA; break;
}
luaL_checktype(this.handle, arg, t);
}
@nogc
bool isType(T)(int index) nothrow
{
return this.type(index) == LuaState.luaValueKindFor!T;
}
@nogc
static LuaValue.Kind luaValueKindFor(T)() pure nothrow
{
import std.typecons : Nullable;
import std.traits : isNumeric, isDynamicArray, isAssociativeArray,
isPointer, KeyType, ValueType,
isInstanceOf, TemplateArgsOf;
static if(is(T == string))
return LuaValue.Kind.text;
else static if(is(T == const(char)[]))
return LuaValue.Kind.text;
else static if(is(T : const(bool)))
return LuaValue.Kind.boolean;
else static if(isNumeric!T)
return LuaValue.Kind.number;
else static if(is(T == typeof(null)) || is(T == LuaNil))
return LuaValue.Kind.nil;
else static if(is(T == LuaTableWeak))
return LuaValue.Kind.table;
else static if(is(T == LuaTable))
return LuaValue.Kind.table;
else static if(isDynamicArray!T)
return LuaValue.Kind.table;
else static if(isAssociativeArray!T)
return LuaValue.Kind.table;
else static if(is(T == LuaCFunc))
return LuaValue.Kind.func;
else static if(is(T == LuaFuncWeak))
return LuaValue.Kind.func;
else static if(is(T == LuaFunc))
return LuaValue.Kind.func;
else static if(isInstanceOf!(Nullable, T))
return luaValueKindFor!(TemplateArgsOf!T[0])();
else static if(isPointer!T || is(T == class))
return LuaValue.Kind.userData;
else static if(is(T == struct))
return LuaValue.Kind.table;
else static assert(false, "Don't know how to convert any LUA values into type: "~T.stringof);
}
void doFile(const char[] file)
{
const status = luaL_dofile(this.handle, file.toStringz);
if(status != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
void doFile(const char[] file, scope ref LuaTable table)
{
const loadStatus = luaL_loadfile(this.handle, file.toStringz);
if(loadStatus != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
table.push();
const fenvResult = lua_setfenv(this.handle, -2);
if(fenvResult == 0)
throw new LuaException("Failed to set function environment");
const callStatus = lua_pcall(this.handle, 0, 0, 0);
if(callStatus != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
void doString(const char[] str)
{
const status = luaL_dostring(this.handle, str.toStringz);
if(status != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
void doString(const char[] str, scope ref LuaTable table)
{
const loadStatus = luaL_loadstring(this.handle, str.toStringz);
if(loadStatus != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
table.push();
const fenvResult = lua_setfenv(this.handle, -2);
if(fenvResult == 0)
throw new LuaException("Failed to set function environment");
const callStatus = lua_pcall(this.handle, 0, 0, 0);
if(callStatus != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
void loadFile(const char[] file)
{
const status = luaL_loadfile(this.handle, file.toStringz);
if(status != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
void loadString(const char[] str)
{
const status = luaL_loadstring(this.handle, str.toStringz);
if(status != LuaStatus.ok)
{
const error = this.get!string(-1);
this.pop(1);
throw new LuaException(error);
}
}
@nogc
ptrdiff_t optInt(int arg, ptrdiff_t default_) nothrow
{
return luaL_optinteger(this.handle, arg, default_);
}
@nogc
LuaNumber optNumber(int arg, LuaNumber default_) nothrow
{
return luaL_optnumber(this.handle, arg, default_);
}
void printStack()
{
writeln("[LUA STACK]");
foreach(i; 0..this.top)
{
const type = lua_type(this.handle, i+1);
writef("\t[%s] \t", i+1);
switch(type)
{
case LUA_TBOOLEAN: writefln("%s\t%s", "BOOL", this.get!bool(i+1)); break;
case LUA_TFUNCTION: writefln("%s\t%s", "FUNC", lua_tocfunction(this.handle, i+1)); break;
case LUA_TLIGHTUSERDATA: writefln("%s\t%s", "LIGHT", lua_touserdata(this.handle, i+1)); break;
case LUA_TNIL: writefln("%s", "NIL"); break;
case LUA_TNUMBER: writefln("%s\t%s", "NUM", this.get!lua_Number(i+1)); break;
case LUA_TSTRING: writefln("%s\t%s", "STR", this.get!(const(char)[])(i+1)); break;
case LUA_TTABLE: writefln("%s", "TABL"); break;
case LUA_TTHREAD: writefln("%s\t%s", "THRD", lua_tothread(this.handle, i+1)); break;
case LUA_TUSERDATA: writefln("%s\t%s", "USER", lua_touserdata(this.handle, i+1)); break;
default: writefln("%s\t%s", "UNKN", type); break;
}
}
}
void push(T)(T value)
{
import std.conv : to;
import std.traits : isNumeric, isDynamicArray, isAssociativeArray, isDelegate, isPointer, isFunction,
PointerTarget, KeyType, ValueType, FieldNameTuple, TemplateOf, TemplateArgsOf;
static if (__traits(compiles, value is null))
{
if (value is null)
{
lua_pushnil(this.handle);
return;
}
}
static if(is(T == typeof(null)) || is(T == LuaNil))
lua_pushnil(this.handle);
else static if(is(T : const(char)[]))
lua_pushlstring(this.handle, value.ptr, value.length);
else static if(isNumeric!T)
lua_pushnumber(this.handle, value.to!lua_Number);
else static if(is(T : const(bool)))
lua_pushboolean(this.handle, value ? 1 : 0);
else static if(isDynamicArray!T)
{
alias ValueT = typeof(value[0]);
lua_createtable(this.handle, 0, value.length.to!int);
foreach(i, v; value)
{
this.push(v);
lua_rawseti(this.handle, -2, cast(int)i+1);
}
}
else static if(isAssociativeArray!T)
{
alias KeyT = KeyType!T;
alias ValueT = ValueType!T;
lua_createtable(this.handle, 0, value.length.to!int);
foreach(k, v; value)
{
this.push(k);
this.push(v);
lua_rawset(this.handle, -3);
}
}
else static if(is(T == LuaTable) || is(T == LuaFunc))
value.push();
else static if(is(T == LuaTableWeak) || is(T == LuaFuncWeak))
this.copy(value.push());
else static if(is(T : lua_CFunction))
lua_pushcfunction(this.handle, value);
else static if(isDelegate!T)
{
lua_pushlightuserdata(this.handle, value.ptr);
lua_pushlightuserdata(this.handle, value.funcptr);
lua_pushcclosure(this.handle, &luaCWrapperSmart!(T, LuaFuncWrapperType.isDelegate), 2);
}
else static if(isPointer!T && isFunction!(PointerTarget!T))
{
lua_pushlightuserdata(this.handle, value);
lua_pushcclosure(this.handle, &luaCWrapperSmart!(T, LuaFuncWrapperType.isFunction), 1);
}
else static if(__traits(isSame, TemplateOf!T, Nullable))
{
if (value.isNull)
lua_pushnil(this.handle);
else
push!(TemplateArgsOf!T)(value.get());
}
else static if(isPointer!T)
lua_pushlightuserdata(this.handle, value);
else static if(is(T == class))
lua_pushlightuserdata(this.handle, cast(void*)value);
else static if(is(T == struct))
{
lua_newtable(this.handle);
static foreach(member; VisibleFieldNameTuple!T)
{
this.push(member);
this.push(getFieldValue!member(value));
lua_settable(this.handle, -3);
}
}
else static assert(false, "Don't know how to push type: "~T.stringof);
}
void push(LuaValue value)
{
value.visit!(
(_){ this.push(_); }
);
}
@nogc
int top() nothrow
{
return lua_gettop(this.handle);
}
@nogc
void pop(int amount) nothrow
{
lua_pop(this.handle, amount);
}
T get(T)(int index)
{
import std.conv : to;
import std.format : format;
import std.traits : isNumeric, isDynamicArray, isAssociativeArray, isPointer, KeyType, ValueType, TemplateOf, TemplateArgsOf, FieldNameTuple;
import std.typecons : isTuple;
static if(is(T == string))
{
if(this.isType!LuaNil(index))
return null;
this.enforceType(LuaValue.Kind.text, index);
size_t len;
auto ptr = lua_tolstring(this.handle, index, &len);
return ptr[0..len].idup;
}
else static if(is(T == const(char)[]))
{
if(this.isType!LuaNil(index))
return null;
this.enforceType(LuaValue.Kind.text, index);
size_t len;
auto ptr = lua_tolstring(this.handle, index, &len);
return ptr[0..len];
}
else static if(is(T : const(bool)))
{
this.enforceType(LuaValue.Kind.boolean, index);
return lua_toboolean(this.handle, index) != 0;
}
else static if(isNumeric!T)
{
this.enforceType(LuaValue.Kind.number, index);
return lua_tonumber(this.handle, index).to!T;
}
else static if(is(T == typeof(null)) || is(T == LuaNil))
{
this.enforceType(LuaValue.Kind.nil, index);
return LuaNil();
}
else static if(is(T == LuaTableWeak))
{
this.enforceType(LuaValue.Kind.table, index);
return T(&this, index);
}
else static if(is(T == LuaTable))
{
this.enforceType(LuaValue.Kind.table, index);
this.copy(index);
return T.makeRef(&this);
}
else static if(isDynamicArray!T)
{
if(this.isType!LuaNil(index))
return null;
this.enforceType(LuaValue.Kind.table, index);
T ret;
ret.length = lua_objlen(this.handle, index);
this.push(null);
const tableIndex = index < 0 ? index - 1 : index;
while(this.next(tableIndex))
{
ret[this.get!size_t(-2) - 1] = this.get!(typeof(ret[0]))(-1);
this.pop(1);
}
return ret;
}
else static if(isAssociativeArray!T)
{
if(this.isType!LuaNil(index))
return null;
this.enforceType(LuaValue.Kind.table, index);
T ret;
this.push(null);
const tableIndex = index < 0 ? index - 1 : index;
while(this.next(tableIndex))
{
ret[this.get!(KeyType!T)(-2)] = this.get!(ValueType!T)(-1);
this.pop(1);
}
return ret;
}
else static if(is(T == LuaCFunc))
{
this.enforceType(LuaValue.Kind.func, index);
return lua_tocfunction(this.handle, index);
}
else static if(is(T == LuaFuncWeak))
{
this.enforceType(LuaValue.Kind.func, index);
return LuaFuncWeak(&this, index);
}
else static if(is(T == LuaFunc))
{
this.enforceType(LuaValue.Kind.func, index);
this.copy(index);
return T.makeRef(&this);
}
else static if(isPointer!T || is(T == class))
{
if(this.isType!LuaNil(index))
return null;
this.enforceType(LuaValue.Kind.userData, index);
return cast(T)lua_touserdata(this.handle, index);
}
else static if(is(T == LuaValue))
{
switch(this.type(index))
{
case LuaValue.Kind.text: return LuaValue(this.get!string(index));
case LuaValue.Kind.number: return LuaValue(this.get!lua_Number(index));
case LuaValue.Kind.boolean: return LuaValue(this.get!bool(index));
case LuaValue.Kind.nil: return LuaValue(this.get!LuaNil(index));
case LuaValue.Kind.table: return LuaValue(this.get!LuaTable(index));
case LuaValue.Kind.func: return LuaValue(this.get!LuaFunc(index));
case LuaValue.Kind.userData: return LuaValue(this.get!(void*)(index));
default: throw new LuaException("Don't know how to convert type into a LuaValue: "~this.type(index).to!string);
}
}
else static if(__traits(isSame, TemplateOf!(T), Nullable))
{
if(this.isType!LuaNil(index))
return T.init;
return cast(T)get!(TemplateArgsOf!(T)[0])(index);
}
else static if (isTuple!T)
{
T ret;
alias params = T.Types;
int idx = 0;
static foreach (i, p; params)
{
idx = cast(int)(i - params.length);
if (params.length != lua_gettop(this.handle))
{
static if(i == 0)
{
return getAsStruct!(T, T.fieldNames)(index);
}
}
else if (this.isType!(params[i])(idx))
{
ret[i] = this.get!(p)(idx);
}
else
{
const firstArgIndex = cast(int)(-params.length);
static if(i == 0)
{
if(this.type(firstArgIndex) == LuaValue.Kind.table)
return getAsStruct!(T, T.fieldNames)(firstArgIndex);
throw new LuaTypeException(
format!(
"When parsing tuple %s, expected value %s to be %s, but it was %s. "
~" Attempted to parse 0th value as a struct instead, but 0th value is not a table."
)(
T.stringof,
idx,
LuaState.luaValueKindFor!(params[i]),
this.type(firstArgIndex),
)
);
}
else
{
throw new LuaTypeException(
format!"When parsing tuple %s, expected value %s to be %s, but it was %s."(
T.stringof,
idx,
LuaState.luaValueKindFor!(params[i]),
this.type(firstArgIndex)
)
);
}
}
}
return ret;
}
else static if(is(T == struct))
{
return getAsStruct!(T, VisibleFieldNameTuple!T)(index);
}
else static assert(false, "Don't know how to convert any LUA values into type: "~T.stringof);
}
T getAsStruct(T, Names ...)(int index)
{
this.enforceType(LuaValue.Kind.table, index);
T ret;
this.push(null);
const tableIndex = index < 0 ? index - 1 : index;
While: while(this.next(tableIndex))
{
const field = this.get!(const(char)[])(-2);