-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMetatables.cs
1013 lines (875 loc) · 34.2 KB
/
Metatables.cs
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
/*
* This file is part of NLua.
*
* Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz.
* Copyright (C) 2012 Megax <http://megax.yeahunter.hu/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using NLua.Method;
using NLua.Extensions;
namespace NLua
{
#if USE_KOPILUA
using LuaCore = KopiLua.Lua;
using LuaState = KopiLua.LuaState;
using LuaNativeFunction = KopiLua.LuaNativeFunction;
#else
using LuaCore = KeraLua.Lua;
using LuaState = KeraLua.LuaState;
using LuaNativeFunction = KeraLua.LuaNativeFunction;
#endif
/*
* Functions used in the metatables of userdata representing
* CLR objects
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class MetaFunctions
{
internal LuaNativeFunction gcFunction, indexFunction, newindexFunction, baseIndexFunction,
classIndexFunction, classNewindexFunction, execDelegateFunction, callConstructorFunction, toStringFunction;
private Dictionary<object, object> memberCache = new Dictionary<object, object> ();
private ObjectTranslator translator;
/*
* __index metafunction for CLR objects. Implemented in Lua.
*/
internal static string luaIndexFunction =
@"local function index(obj,name)
local meta=getmetatable(obj)
local cached=meta.cache[name]
if cached ~= nil then
return cached
else
local value,isFunc = get_object_member(obj,name)
if isFunc then
meta.cache[name]=value
end
return value
end
end
return index";
public MetaFunctions (ObjectTranslator translator)
{
this.translator = translator;
gcFunction = new LuaNativeFunction (MetaFunctions.CollectObject);
toStringFunction = new LuaNativeFunction (MetaFunctions.ToStringLua);
indexFunction = new LuaNativeFunction (MetaFunctions.GetMethod);
newindexFunction = new LuaNativeFunction (MetaFunctions.SetFieldOrProperty);
baseIndexFunction = new LuaNativeFunction (MetaFunctions.GetBaseMethod);
callConstructorFunction = new LuaNativeFunction (MetaFunctions.CallConstructor);
classIndexFunction = new LuaNativeFunction (MetaFunctions.GetClassMethod);
classNewindexFunction = new LuaNativeFunction (MetaFunctions.SetClassFieldOrProperty);
execDelegateFunction = new LuaNativeFunction (MetaFunctions.RunFunctionDelegate);
}
/*
* __call metafunction of CLR delegates, retrieves and calls the delegate.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int RunFunctionDelegate (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return RunFunctionDelegate (luaState, translator);
}
private static int RunFunctionDelegate (LuaState luaState, ObjectTranslator translator)
{
LuaNativeFunction func = (LuaNativeFunction)translator.GetRawNetObject (luaState, 1);
LuaLib.LuaRemove (luaState, 1);
return func (luaState);
}
/*
* __gc metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int CollectObject (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return CollectObject (luaState, translator);
}
private static int CollectObject (LuaState luaState, ObjectTranslator translator)
{
int udata = LuaLib.LuaNetRawNetObj (luaState, 1);
if (udata != -1)
translator.CollectObject (udata);
return 0;
}
/*
* __tostring metafunction of CLR objects.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int ToStringLua (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
return ToStringLua (luaState, translator);
}
private static int ToStringLua (LuaState luaState, ObjectTranslator translator)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj != null)
translator.Push (luaState, obj.ToString () + ": " + obj.GetHashCode ().ToString());
else
LuaLib.LuaPushNil (luaState);
return 1;
}
/// <summary>
/// Debug tool to dump the lua stack
/// </summary>
/// FIXME, move somewhere else
public static void DumpStack (ObjectTranslator translator, LuaState luaState)
{
int depth = LuaLib.LuaGetTop (luaState);
#if WINDOWS_PHONE
Debug.WriteLine("lua stack depth: {0}", depth);
#elif !SILVERLIGHT
Debug.Print ("lua stack depth: {0}", depth);
#endif
for (int i = 1; i <= depth; i++) {
var type = LuaLib.LuaType (luaState, i);
// we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types
string typestr = (type == LuaTypes.Table) ? "table" : LuaLib.LuaTypeName (luaState, type);
string strrep = LuaLib.LuaToString (luaState, i).ToString ();
if (type == LuaTypes.UserData) {
object obj = translator.GetRawNetObject (luaState, i);
strrep = obj.ToString ();
}
#if WINDOWS_PHONE
Debug.WriteLine("{0}: ({1}) {2}", i, typestr, strrep);
#elif !SILVERLIGHT
Debug.Print ("{0}: ({1}) {2}", i, typestr, strrep);
#endif
}
}
/*
* Called by the __index metafunction of CLR objects in case the
* method is not cached or it is a field/property/event.
* Receives the object and the member name as arguments and returns
* either the value of the member or a delegate to call it.
* If the member does not exist returns nil.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int GetMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetMethodInternal (luaState);
}
private int GetMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
return 1;
}
object index = translator.GetObject (luaState, 2);
//var indexType = index.GetType();
string methodName = index as string; // will be null if not a string arg
var objType = obj.GetType ();
// Handle the most common case, looking up the method by name.
// CP: This will fail when using indexers and attempting to get a value with the same name as a property of the object,
// ie: xmlelement['item'] <- item is a property of xmlelement
try {
if (!string.IsNullOrEmpty(methodName) && IsMemberPresent (objType, methodName))
return GetMember (luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
} catch {
}
// Try to access by array if the type is right and index is an int (lua numbers always come across as double)
if (objType.IsArray && index is double) {
int intIndex = (int)((double)index);
if (objType.UnderlyingSystemType == typeof(float[])) {
float[] arr = ((float[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (objType.UnderlyingSystemType == typeof(double[])) {
double[] arr = ((double[])obj);
translator.Push (luaState, arr [intIndex]);
} else if (objType.UnderlyingSystemType == typeof(int[])) {
int[] arr = ((int[])obj);
translator.Push (luaState, arr [intIndex]);
} else {
object[] arr = (object[])obj;
translator.Push (luaState, arr [intIndex]);
}
} else {
// Try to use get_Item to index into this .net object
var methods = objType.GetMethods ();
foreach (var mInfo in methods) {
if (mInfo.Name == "get_Item") {
//check if the signature matches the input
if (mInfo.GetParameters ().Length == 1) {
var getter = mInfo;
var actualParms = (getter != null) ? getter.GetParameters () : null;
if (actualParms == null || actualParms.Length != 1) {
translator.ThrowError (luaState, "method not found (or no indexer): " + index);
LuaLib.LuaPushNil (luaState);
} else {
// Get the index in a form acceptable to the getter
index = translator.GetAsType (luaState, 2, actualParms [0].ParameterType);
object[] args = new object[1];
// Just call the indexer - if out of bounds an exception will happen
args [0] = index;
try {
object result = getter.Invoke (obj, args);
translator.Push (luaState, result);
} catch (TargetInvocationException e) {
// Provide a more readable description for the common case of key not found
if (e.InnerException is KeyNotFoundException)
translator.ThrowError (luaState, "key '" + index + "' not found ");
else
translator.ThrowError (luaState, "exception indexing '" + index + "' " + e.Message);
LuaLib.LuaPushNil (luaState);
}
}
}
}
}
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/*
* __index metafunction of base classes (the base field of Lua tables).
* Adds a prefix to the method name to call the base version of the method.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int GetBaseMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetBaseMethodInternal (luaState);
}
private int GetBaseMethodInternal (LuaState luaState)
{
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null) {
translator.ThrowError (luaState, "trying to index an invalid object reference");
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
GetMember (luaState, obj.GetType (), obj, "__luaInterface_base_" + methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
LuaLib.LuaSetTop (luaState, -2);
if (LuaLib.LuaType (luaState, -1) == LuaTypes.Nil) {
LuaLib.LuaSetTop (luaState, -2);
return GetMember (luaState, obj.GetType (), obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase);
}
LuaLib.LuaPushBoolean (luaState, false);
return 2;
}
/// <summary>
/// Does this method exist as either an instance or static?
/// </summary>
/// <param name="objType"></param>
/// <param name="methodName"></param>
/// <returns></returns>
bool IsMemberPresent (IReflect objType, string methodName)
{
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
if (cachedMember != null)
return true;
//CP: Removed NonPublic binding search
var members = objType.GetMember (methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
return (members.Length > 0);
}
/*
* Pushes the value of a member or a delegate to call it, depending on the type of
* the member. Works with static or instance members.
* Uses reflection to find members, and stores the reflected MemberInfo object in
* a cache (indexed by the type of the object and the name of the member).
*/
private int GetMember (LuaState luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType)
{
bool implicitStatic = false;
MemberInfo member = null;
object cachedMember = CheckMemberCache (memberCache, objType, methodName);
//object cachedMember=null;
if (cachedMember is LuaNativeFunction) {
translator.PushFunction (luaState, (LuaNativeFunction)cachedMember);
translator.Push (luaState, true);
return 2;
} else if (cachedMember != null)
member = (MemberInfo)cachedMember;
else {
//CP: Removed NonPublic binding search
var members = objType.GetMember (methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0)
member = members [0];
else {
// If we can't find any suitable instance members, try to find them as statics - but we only want to allow implicit static
// lookups for fields/properties/events -kevinh
//CP: Removed NonPublic binding search and made case insensitive
members = objType.GetMember (methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0) {
member = members [0];
implicitStatic = true;
}
}
}
if (member != null) {
if (member.MemberType == MemberTypes.Field) {
var field = (FieldInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
translator.Push (luaState, field.GetValue (obj));
} catch {
LuaLib.LuaPushNil (luaState);
}
} else if (member.MemberType == MemberTypes.Property) {
var property = (PropertyInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
try {
object val = property.GetValue (obj, null);
translator.Push (luaState, val);
} catch (ArgumentException) {
// If we can't find the getter in our class, recurse up to the base class and see
// if they can help.
if (objType is Type && !(((Type)objType) == typeof(object)))
return GetMember (luaState, ((Type)objType).BaseType, obj, methodName, bindingType);
else
LuaLib.LuaPushNil (luaState);
} catch (TargetInvocationException e) { // Convert this exception into a Lua error
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
}
} else if (member.MemberType == MemberTypes.Event) {
var eventInfo = (EventInfo)member;
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
translator.Push (luaState, new RegisterEventHandler (translator.pendingEvents, obj, eventInfo));
} else if (!implicitStatic) {
if (member.MemberType == MemberTypes.NestedType) {
// kevinh - added support for finding nested types
// cache us
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, member);
// Find the name of our class
string name = member.Name;
var dectype = member.DeclaringType;
// Build a new long name and try to find the type by name
string longname = dectype.FullName + "+" + name;
var nestedType = translator.FindType (longname);
translator.PushType (luaState, nestedType);
} else {
// Member type must be 'method'
var wrapper = new LuaNativeFunction ((new LuaMethodWrapper (translator, objType, methodName, bindingType)).invokeFunction);
if (cachedMember == null)
SetMemberCache (memberCache, objType, methodName, wrapper);
translator.PushFunction (luaState, wrapper);
translator.Push (luaState, true);
return 2;
}
} else {
// If we reach this point we found a static method, but can't use it in this context because the user passed in an instance
translator.ThrowError (luaState, "can't pass instance to static method " + methodName);
LuaLib.LuaPushNil (luaState);
}
} else {
// kevinh - we want to throw an exception because meerly returning 'nil' in this case
// is not sufficient. valid data members may return nil and therefore there must be some
// way to know the member just doesn't exist.
translator.ThrowError (luaState, "unknown member name " + methodName);
LuaLib.LuaPushNil (luaState);
}
// push false because we are NOT returning a function (see luaIndexFunction)
translator.Push (luaState, false);
return 2;
}
/*
* Checks if a MemberInfo object is cached, returning it or null.
*/
private object CheckMemberCache (Dictionary<object, object> memberCache, IReflect objType, string memberName)
{
object members = null;
if (memberCache.TryGetValue(objType, out members))
{
var membersDict = members as Dictionary<object, object>;
object memberValue = null;
if (members != null && membersDict.TryGetValue(memberName, out memberValue))
{
return memberValue;
}
}
return null;
}
/*
* Stores a MemberInfo object in the member cache.
*/
private void SetMemberCache (Dictionary<object, object> memberCache, IReflect objType, string memberName, object member)
{
Dictionary<object, object> members = null;
object memberCacheValue = null;
if (memberCache.TryGetValue(objType, out memberCacheValue)) {
members = (Dictionary<object, object>)memberCacheValue;
} else {
members = new Dictionary<object, object>();
memberCache[objType] = members;
}
}
/*
* __newindex metafunction of CLR objects. Receives the object,
* the member name and the value to be stored as arguments. Throws
* and error if the assignment is invalid.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int SetFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetFieldOrPropertyInternal (luaState);
}
private int SetFieldOrPropertyInternal (LuaState luaState)
{
object target = translator.GetRawNetObject (luaState, 1);
if (target == null) {
translator.ThrowError (luaState, "trying to index and invalid object reference");
return 0;
}
var type = target.GetType ();
// First try to look up the parameter as a property name
string detailMessage;
bool didMember = TrySetMember (luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage);
if (didMember)
return 0; // Must have found the property name
// We didn't find a property name, now see if we can use a [] style this accessor to set array contents
try {
if (type.IsArray && LuaLib.LuaIsNumber (luaState, 2)) {
int index = (int)LuaLib.LuaToNumber (luaState, 2);
var arr = (Array)target;
object val = translator.GetAsType (luaState, 3, arr.GetType ().GetElementType ());
arr.SetValue (val, index);
} else {
// Try to see if we have a this[] accessor
var setter = type.GetMethod ("set_Item");
if (setter != null) {
var args = setter.GetParameters ();
var valueType = args [1].ParameterType;
// The new val ue the user specified
object val = translator.GetAsType (luaState, 3, valueType);
var indexType = args [0].ParameterType;
object index = translator.GetAsType (luaState, 2, indexType);
object[] methodArgs = new object[2];
// Just call the indexer - if out of bounds an exception will happen
methodArgs [0] = index;
methodArgs [1] = val;
setter.Invoke (target, methodArgs);
} else
translator.ThrowError (luaState, detailMessage); // Pass the original message from trySetMember because it is probably best
}
#if !SILVERLIGHT
} catch (SEHException) {
// If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it
throw;
#endif
} catch (Exception e) {
ThrowError (luaState, e);
}
return 0;
}
/// <summary>
/// Tries to set a named property or field
/// </summary>
/// <param name="luaState"></param>
/// <param name="targetType"></param>
/// <param name="target"></param>
/// <param name="bindingType"></param>
/// <returns>false if unable to find the named member, true for success</returns>
private bool TrySetMember (LuaState luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage)
{
detailMessage = null; // No error yet
// If not already a string just return - we don't want to call tostring - which has the side effect of
// changing the lua typecode to string
// Note: We don't use isstring because the standard lua C isstring considers either strings or numbers to
// be true for isstring.
if (LuaLib.LuaType (luaState, 2) != LuaTypes.String) {
detailMessage = "property names must be strings";
return false;
}
// We only look up property names by string
string fieldName = LuaLib.LuaToString (luaState, 2).ToString ();
if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter (fieldName [0]) || fieldName [0] == '_')) {
detailMessage = "invalid property name";
return false;
}
// Find our member via reflection or the cache
var member = (MemberInfo)CheckMemberCache (memberCache, targetType, fieldName);
if (member == null) {
//CP: Removed NonPublic binding search and made case insensitive
var members = targetType.GetMember (fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*| BindingFlags.NonPublic*/);
if (members.Length > 0) {
member = members [0];
SetMemberCache (memberCache, targetType, fieldName, member);
} else {
detailMessage = "field or property '" + fieldName + "' does not exist";
return false;
}
}
if (member.MemberType == MemberTypes.Field) {
var field = (FieldInfo)member;
object val = translator.GetAsType (luaState, 3, field.FieldType);
try {
field.SetValue (target, val);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
} else if (member.MemberType == MemberTypes.Property) {
var property = (PropertyInfo)member;
object val = translator.GetAsType (luaState, 3, property.PropertyType);
try {
property.SetValue (target, val, null);
} catch (Exception e) {
ThrowError (luaState, e);
}
// We did a call
return true;
}
detailMessage = "'" + fieldName + "' is not a .net field or property";
return false;
}
/*
* Writes to fields or properties, either static or instance. Throws an error
* if the operation is invalid.
*/
private int SetMember (LuaState luaState, IReflect targetType, object target, BindingFlags bindingType)
{
string detail;
bool success = TrySetMember (luaState, targetType, target, bindingType, out detail);
if (!success)
translator.ThrowError (luaState, detail);
return 0;
}
/// <summary>
/// Convert a C# exception into a Lua error
/// </summary>
/// <param name="e"></param>
/// We try to look into the exception to give the most meaningful description
void ThrowError (LuaState luaState, Exception e)
{
// If we got inside a reflection show what really happened
var te = e as TargetInvocationException;
if (te != null)
e = te.InnerException;
translator.ThrowError (luaState, e);
}
/*
* __index metafunction of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int GetClassMethod (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.GetClassMethodInternal (luaState);
}
private int GetClassMethodInternal (LuaState luaState)
{
IReflect klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is IReflect)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (IReflect)obj;
if (LuaLib.LuaIsNumber (luaState, 2)) {
int size = (int)LuaLib.LuaToNumber (luaState, 2);
translator.Push (luaState, Array.CreateInstance (klass.UnderlyingSystemType, size));
return 1;
} else {
string methodName = LuaLib.LuaToString (luaState, 2).ToString ();
if (string.IsNullOrEmpty(methodName)) {
LuaLib.LuaPushNil (luaState);
return 1;
} //CP: Ignore case
else
return GetMember (luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
}
}
/*
* __newindex function of type references, works on static members.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int SetClassFieldOrProperty (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.SetClassFieldOrPropertyInternal (luaState);
}
private int SetClassFieldOrPropertyInternal (LuaState luaState)
{
IReflect target;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is IReflect)) {
translator.ThrowError (luaState, "trying to index an invalid type reference");
return 0;
} else
target = (IReflect)obj;
return SetMember (luaState, target, null, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase);
}
/*
* __call metafunction of type references. Searches for and calls
* a constructor for the type. Returns nil if the constructor is not
* found or if the arguments are invalid. Throws an error if the constructor
* generates an exception.
*/
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (LuaNativeFunction))]
#endif
[System.Runtime.InteropServices.AllowReversePInvokeCalls]
private static int CallConstructor (LuaState luaState)
{
var translator = ObjectTranslatorPool.Instance.Find (luaState);
var instance = translator.MetaFunctionsInstance;
return instance.CallConstructorInternal (luaState);
}
private int CallConstructorInternal (LuaState luaState)
{
var validConstructor = new MethodCache ();
IReflect klass;
object obj = translator.GetRawNetObject (luaState, 1);
if (obj == null || !(obj is IReflect)) {
translator.ThrowError (luaState, "trying to call constructor on an invalid type reference");
LuaLib.LuaPushNil (luaState);
return 1;
} else
klass = (IReflect)obj;
LuaLib.LuaRemove (luaState, 1);
var constructors = klass.UnderlyingSystemType.GetConstructors ();
foreach (var constructor in constructors) {
bool isConstructor = MatchParameters (luaState, constructor, ref validConstructor);
if (isConstructor) {
try {
translator.Push (luaState, constructor.Invoke (validConstructor.args));
} catch (TargetInvocationException e) {
ThrowError (luaState, e);
LuaLib.LuaPushNil (luaState);
} catch {
LuaLib.LuaPushNil (luaState);
}
return 1;
}
}
string constructorName = (constructors.Length == 0) ? "unknown" : constructors [0].Name;
translator.ThrowError (luaState, String.Format ("{0} does not contain constructor({1}) argument match",
klass.UnderlyingSystemType, constructorName));
LuaLib.LuaPushNil (luaState);
return 1;
}
private static bool IsInteger(double x) {
return Math.Ceiling(x) == x;
}
internal Array TableToArray (object luaParamValue, Type paramArrayType)
{
Array paramArray;
if (luaParamValue is LuaTable) {
LuaTable table = (LuaTable)luaParamValue;
IDictionaryEnumerator tableEnumerator = table.GetEnumerator ();
tableEnumerator.Reset ();
paramArray = Array.CreateInstance (paramArrayType, table.Values.Count);
int paramArrayIndex = 0;
while (tableEnumerator.MoveNext ()) {
object value = tableEnumerator.Value;
if (paramArrayType == typeof (object)) {
if (value != null && value.GetType () == typeof (double) && IsInteger ((double)value))
value = Convert.ToInt32 ((double)value);
}
#if SILVERLIGHT
paramArray.SetValue (Convert.ChangeType (value, paramArrayType, System.Globalization.CultureInfo.InvariantCulture), paramArrayIndex);
#else
paramArray.SetValue (Convert.ChangeType (value, paramArrayType), paramArrayIndex);
#endif
paramArrayIndex++;
}
} else {
paramArray = Array.CreateInstance (paramArrayType, 1);
paramArray.SetValue (luaParamValue, 0);
}
return paramArray;
}
/*
* Matches a method against its arguments in the Lua stack. Returns
* if the match was succesful. It it was also returns the information
* necessary to invoke the method.
*/
internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
{
ExtractValue extractValue;
bool isMethod = true;
var paramInfo = method.GetParameters ();
int currentLuaParam = 1;
int nLuaParams = LuaLib.LuaGetTop (luaState);
var paramList = new List<object> ();
var outList = new List<int> ();
var argTypes = new List<MethodArgs> ();
foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT
if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params
#else
if (currentNetParam.IsOut) // Skips out params
#endif
{
paramList.Add (null);
outList.Add (paramList.LastIndexOf (null));
} else if (currentLuaParam > nLuaParams) { // Adds optional parameters
if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else {
isMethod = false;
break;
}
} else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) { // Type checking
var value = extractValue (luaState, currentLuaParam);
paramList.Add (value);
int index = paramList.LastIndexOf (value);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
argTypes.Add (methodArg);
if (currentNetParam.ParameterType.IsByRef)
outList.Add (index);
currentLuaParam++;
} // Type does not match, ignore if the parameter is optional
else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {
object luaParamValue = extractValue (luaState, currentLuaParam);
var paramArrayType = currentNetParam.ParameterType.GetElementType ();
Array paramArray = TableToArray (luaParamValue, paramArrayType);
paramList.Add (paramArray);
int index = paramList.LastIndexOf (paramArray);
var methodArg = new MethodArgs ();
methodArg.index = index;
methodArg.extractValue = extractValue;
methodArg.isParamsArray = true;
methodArg.paramsArrayType = paramArrayType;
argTypes.Add (methodArg);
currentLuaParam++;
} else if (currentNetParam.IsOptional)
paramList.Add (currentNetParam.DefaultValue);
else { // No match
isMethod = false;
break;
}
}
if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
isMethod = false;
if (isMethod) {
methodCache.args = paramList.ToArray ();
methodCache.cachedMethod = method;
methodCache.outList = outList.ToArray ();
methodCache.argTypes = argTypes.ToArray ();
}
return isMethod;
}
/// <summary>
/// CP: Fix for operator overloading failure
/// Returns true if the type is set and assigns the extract value
/// </summary>
/// <param name="luaState"></param>
/// <param name="currentLuaParam"></param>
/// <param name="currentNetParam"></param>
/// <param name="extractValue"></param>
/// <returns></returns>
private bool IsTypeCorrect (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
try {
return (extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, currentNetParam.ParameterType)) != null;
} catch {
extractValue = null;
Debug.WriteLine ("Type wasn't correct");
return false;
}
}
private bool IsParamsArray (LuaState luaState, int currentLuaParam, ParameterInfo currentNetParam, out ExtractValue extractValue)
{
extractValue = null;
if (currentNetParam.GetCustomAttributes (typeof(ParamArrayAttribute), false).Length > 0) {
LuaTypes luaType;
try {
luaType = LuaLib.LuaType (luaState, currentLuaParam);
} catch (Exception ex) {
Debug.WriteLine ("Could not retrieve lua type while attempting to determine params Array Status.");
Debug.WriteLine (ex.Message);
extractValue = null;
return false;
}
if (luaType == LuaTypes.Table) {
try {
extractValue = translator.typeChecker.GetExtractor (typeof(LuaTable));
} catch (Exception/* ex*/) {
Debug.WriteLine ("An error occurred during an attempt to retrieve a LuaTable extractor while checking for params array status.");
}
if (extractValue != null) {
return true;
}
} else {
var paramElementType = currentNetParam.ParameterType.GetElementType ();
try {
extractValue = translator.typeChecker.CheckLuaType (luaState, currentLuaParam, paramElementType);
} catch (Exception/* ex*/) {
Debug.WriteLine (string.Format ("An error occurred during an attempt to retrieve an extractor ({0}) while checking for params array status.", paramElementType.FullName));