-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathLuaUtility.cs
1965 lines (1832 loc) · 62.1 KB
/
LuaUtility.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using UnityEngine;
using UnityEngine.Assertions;
public class LuaUtility
{
public class ToLuaSetting
{
public bool SkipProperty = false;
public List<string> propertyWhiteList;
public int MaxLevel = -1;
public bool ExportRootType = false;//是否导出传入的类类型信息
}
private static bool isShowLog = false;
static string TabStr = "\t";
static LexState cur_ls_in_parse_for_debug = null;
public static bool IsShowLog { get => isShowLog; set => isShowLog = value; }
public static string ToLua(object obj, ToLuaSetting setting=null)
{
return ToLua(obj, 1, null, setting);
}
static readonly Type list_type = typeof(IList);
static readonly Type dic_type = typeof(IDictionary);
private static string ToLua(object obj, int level, Type obj_member_type, ToLuaSetting setting)
{
if (setting != null && setting.MaxLevel != -1 && level >= setting.MaxLevel)
return "";
if (obj == null)
return "nil";
Type type = obj.GetType();
StringBuilder content = new StringBuilder();
string tab_str = GetStrMutiple(TabStr, level);
if (type.IsPrimitive)
{
if (obj is bool)
{
content.Append(((bool)obj)?"true":"false");
}
else
content.Append(obj.ToString());
}
else if (type == typeof(string))
{
// var str = obj.ToString().Replace("\n", "\\\n");
var str = obj.ToString();
var symbol = "\"";
var symbol_end = symbol;
if (str.IndexOf("\n") != -1)
{
symbol = "[[";
symbol_end = "]]";
}
content.Append(symbol + str + symbol_end);
}
else if (type.IsEnum)
{
content.Append((int)obj);
}
else if (list_type.IsAssignableFrom(type))
{
content.Append("{\n");
IEnumerable list_info = obj as IEnumerable;
Type member_type = null;
var gneric_args = type.GetGenericArguments();
if (gneric_args != null && gneric_args.Length > 0)
member_type = gneric_args[0];
else
member_type = type.GetElementType();
foreach (var list_item in list_info)
{
content.Append(tab_str);
content.Append(ToLua(list_item, level+1, member_type, setting));
content.Append(",\n");
}
content.Append(GetStrMutiple(TabStr, level-1));
content.Append("}");
}
else if (dic_type.IsAssignableFrom(type))
{
content.Append("{\n");
IDictionary dic_info = obj as IDictionary;
foreach (var item in dic_info)
{
var itemKey = item.GetType().GetProperty("Key").GetValue(item, null);
var itemKeyType = dic_info.GetType().GetGenericArguments()[0];
var itemValue = item.GetType().GetProperty("Value").GetValue(item, null);
var itemValueType = dic_info.GetType().GetGenericArguments()[1];
string itemKeyStr;
if (itemKeyType == typeof(string))
itemKeyStr = "[\""+itemKey.ToString()+"\"]";
else
itemKeyStr = "["+itemKey.ToString()+"]";
content.Append(tab_str);
content.Append(itemKeyStr + " = ");
content.Append(ToLua(itemValue, level+1, itemValueType, setting));
content.Append(",\n");
}
content.Append(GetStrMutiple(TabStr, level-1));
content.Append("}");
}
else
{
content.Append("{\n");
// Type type = obj.GetType();
var contractAttr = type.GetCustomAttribute(typeof(DataContractAttribute));
//如果类有 DataContract 特性的话,就只导出其带有 DataMember 特性的字段,否则导出所有 public 字段
bool isNeedAttr = contractAttr != null;
MemberInfo[] members = type.GetMembers();
// UnityEngine.Debug.Log("members.Length : "+members.Length.ToString());
if (members != null && members.Length > 0)
{
//只有实际类型和定义的类型不一样才需要加上类型信息,即多态时才加
if ((obj_member_type != type && level > 1) || (level == 1 && setting != null && setting.ExportRootType))
content.Append(tab_str + string.Format("[\"$type\"] = \"{0}\",\n", type.FullName+", "+type.Assembly.GetName().Name));
foreach (MemberInfo p in members)
{
var isNeedExport = true;
if (isNeedAttr)
{
object[] objAttrs = p.GetCustomAttributes(typeof(DataMemberAttribute), true);
isNeedExport = objAttrs != null && objAttrs.Length > 0;
}
if (isNeedExport)
{
object[] objAttrs = p.GetCustomAttributes(typeof(HideInInspector), true);
isNeedExport = objAttrs == null || objAttrs.Length <= 0;
}
if (isNeedExport)
{
// Debug.LogFormat("LuaUtility[107:06] p.ToString():{0}", p.ToString());
object obj_value = null;
FieldInfo field = p as FieldInfo;
Type member_type = null;
if(field!=null && !field.IsStatic)
{
obj_value = field.GetValue(obj);
member_type = field.FieldType;
}
else if (setting == null || !setting.SkipProperty || (setting.propertyWhiteList != null && setting.propertyWhiteList.Contains(p.Name)))
{
PropertyInfo pro = p as PropertyInfo;
if (pro != null && pro.CanRead && pro.CanWrite)
{
member_type = pro.PropertyType;
// Debug.Log("pro name : "+pro.Name+" "+type.Name+" mtype:"+pro.MemberType);
try {
obj_value = pro.GetValue(obj);
}
catch{}
}
}
if (obj_value != null)
{
content.Append(tab_str + p.Name + " = ");
content.Append(ToLua(obj_value, level+1, member_type, setting));
content.Append(",\n");
}
}
};
}
content.Append(GetStrMutiple(TabStr, level-1));
content.Append("}");
}
return content.ToString();
}
public static string GetStrMutiple(string str, int num)
{
string result = "";
for (int i = 0; i < num; i++)
{
result += str;
}
return result;
}
//---------------------------Lua->C#---------------------------------
public static void ThrowError(string err_str)
{
Debug.LogError(err_str);
throw new System.InvalidOperationException(err_str);
}
public class Token
{
public int token;
public string str;
public long i;
public double d;
public override string ToString()
{
return string.Format("Token:{0} str:{1} i:{2} d:{3}", token, str, i, d);
}
}
public enum KeyWord
{
Local,
Nil,
Return,
True,
False,
Dots,
Equal,
String,
Name,
Integer,
FLOAT,
Concat,
Function,
End,
IF,
While,
For,
EOZ
}
public class LexState : ICloneable
{
public static int EOZ = -1;
public int current;
public int code_i;
public Token t; /* current token */
public Token lookahead; /* look ahead token */
public string code;
private int linenumber;
private Dictionary<string,KeyWord> reserved_words;
static int[] LuaI_CType = new int[]{
0x00, /* EOZ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */
0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
private static int ALPHABIT = 0;
private static int DIGITBIT = 1;
private static int PRINTBIT = 2;
private static int SPACEBIT = 3;
private static int XDIGITBIT = 4;
public LexState(string _code)
{
InitReserved();
code = _code;
code_i = -1;
linenumber = 1;
NextChar();
MoveToNextToken();
}
public void UpdateData(LexState ls)
{
this.code = ls.code;
this.code_i = ls.code_i;
this.t = ls.t;
this.lookahead = ls.lookahead;
this.current = ls.current;
}
public string Dump()
{
StringBuilder sb = new StringBuilder();
sb.Append("line : "+linenumber+" current : "+current+" token:"+t.ToString()+" code_i:"+code_i+" lookahead:"+(lookahead!=null?lookahead.ToString():"null"));
return sb.ToString();
}
private void InitReserved()
{
reserved_words = new Dictionary<string, KeyWord>();
reserved_words.Add("local", KeyWord.Local);
reserved_words.Add("return", KeyWord.Return);
reserved_words.Add("false", KeyWord.False);
reserved_words.Add("true", KeyWord.True);
reserved_words.Add("function", KeyWord.Function);
reserved_words.Add("end", KeyWord.End);
reserved_words.Add("if", KeyWord.IF);
reserved_words.Add("while", KeyWord.While);
reserved_words.Add("for", KeyWord.For);
reserved_words.Add("nil", KeyWord.Nil);
}
private void NextChar()
{
code_i++;
if (code_i < code.Length)
current = code[code_i];
else
current = EOZ;
}
public Token MoveToNextToken()
{
if (lookahead != null)
{
t = lookahead;
lookahead = null;
}
else
{
t = new Token();
t.token = ReadToken(ref t);
}
return null;
}
public Token ReadAheadToken()
{
lookahead = new Token();
lookahead.token = ReadToken(ref lookahead);
return lookahead;
}
private KeyWord TryGetReserved(string str)
{
if (reserved_words.ContainsKey(str))
return reserved_words[str];
else
return KeyWord.Name;
}
private bool CheckNext1(char set)
{
if (current == set)
{
NextChar();
return true;
}
return false;
}
private bool CheckNext2(string set)
{
if (current == set[0] || current == set[1])
{
NextChar();
return true;
}
return false;
}
public bool TestNext(int c)
{
if (t.token == c)
{
NextChar();
return true;
}
return false;
}
private bool TestProp(int c, int p)
{
var ret = (LuaI_CType[(int)c+1] & p);
return ret != 0;
}
private int GetMask(int i)
{
return 1<<i;
}
public bool IsAlpha(int c)
{
return TestProp(c, GetMask(ALPHABIT));
}
public bool IsAlphaNum(int c)
{
return TestProp(c, GetMask(ALPHABIT) | GetMask(DIGITBIT));
}
public bool IsDigit(int c)
{
return TestProp(c, GetMask(DIGITBIT));
}
private void ReadString(ref Token token, int del)
{
void OnlySave(ref Token _token, string str)
{
_token.str = _token.str.Substring(0, _token.str.Length-1);
_token.str += str;
}
void ReadSave(ref Token _token, string str)
{
OnlySave(ref _token, str);
NextChar();
}
NextChar();
int start_i = code_i;
token.str = "";
while (current != del)
{
if (current == EOZ || current == '\n' || current == '\r')
{
LuaUtility.ThrowError("unfinished string");
break;
}
else if (current == '\\')//CAT_TODO:处理\\符号的\x:十六进制 \u八进制 \z
{
token.str += code.Substring(start_i, code_i-start_i+1);
// Debug.LogFormat("LuaUtility[391:54] token.str:{0}", token.str+" start_i:"+start_i);
NextChar();
start_i = code_i;
// Debug.LogFormat("LuaUtility[420:05] current:{0} start_i:{1}", current, start_i);
if (current == 'a' || current == 'b' || current == 'f' || current == 'n' || current == 'r' || current == 't' || current == 'v' )
{
ReadSave(ref token, "\\"+current);
}
else if (current == '\n' || current == '\r')
{
IncLineNumber();
OnlySave(ref token, "\n");
}
else if (current == '\\' || current == '\"' || current == '\'')
{
ReadSave(ref token, ((char)current).ToString());
}
start_i = code_i;
}
else
{
NextChar();
}
}
token.str += code.Substring(start_i, code_i-start_i);
// Debug.Log("read string : "+token.str+" start_i:"+start_i+" end_i:"+code_i);
NextChar();
}
private int ReadNumeral(ref Token token, bool is_decimal)
{
string expo = "Ee";
int start_i = code_i;
var first = current;
NextChar();
if (first == '0' && CheckNext2("xX"))
expo = "Pp";
while (true)
{
if (CheckNext2(expo))
CheckNext2("-+");
if (IsDigit(current))
NextChar();
else if (current == '.')
NextChar();
else
break;
}
var num_str = code.Substring(start_i, code_i-start_i);
if (is_decimal)
num_str = "0." + num_str;
long ret_i;
var isInt = long.TryParse(num_str, out ret_i);
if (isInt)
{
token.i = ret_i;
return (int)KeyWord.Integer;
}
else
{
double ret_d;
num_str = num_str.Replace("e", "E");
var isDouble = double.TryParse(num_str, out ret_d);
if (isDouble)
{
token.d = ret_d;
}
else
{
var err_str = string.Format("malformed number {0} in code {1}~{2}", num_str, start_i, code_i);
Debug.LogError(err_str);
}
return (int)KeyWord.FLOAT;
}
}
private int SkipSep()
{
int count = 0;
int s = current;
NextChar();
while (current == '=')
{
NextChar();
count++;
}
return (current == s) ? count : (-count)-1;
}
private void IncLineNumber()
{
int old = current;
Assert.IsTrue(CurrentIsNewLine());
NextChar();
if (CurrentIsNewLine() && current != old)
NextChar();
if (++linenumber >= int.MaxValue)
Assert.IsTrue(false, "line number too much");
}
private bool CurrentIsNewLine()
{
return current == '\n' || current == '\r';
}
private string ReadLongString(ref Token token, int sep)
{
bool isString = token != null;
NextChar();
int start_i = code_i;
int end_i = code_i;
if (CurrentIsNewLine())
IncLineNumber();
while (true)
{
if (current == EOZ)
{
ThrowError("unfinished long "+(isString?"string":"comment")+", ls:"+Dump());
break;
}
else if (current == ']')
{
end_i = code_i;
if (SkipSep() == sep)
{
NextChar();
break;
}
}
else if (current == '\n' || current == '\r')
{
IncLineNumber();
end_i = code_i;
}
else
{
NextChar();
}
}
return code.Substring(start_i, end_i-start_i-(isString?0:2));
}
public int ReadToken(ref Token token)
{
int loop_max = 5000;
while (loop_max > 0)
{
loop_max--;
if (current == '\n' || current == '\r')
{
IncLineNumber();
}
else if (current == ' ' || current == '\f' || current == '\t' || current == '\v')
{
NextChar();
}
else if (current == '-')
{
NextChar();
if (current != '-')
return '-';
NextChar();
if (current == '[')
{ /* long comment? */
int sep = SkipSep();
if (sep >= 0)
{
Token emptyToken = null;
var longStr = ReadLongString(ref emptyToken, sep);
// Debug.Log("ReadToken comment longStr : "+longStr);
}
}
while (!CurrentIsNewLine() && current != EOZ)
NextChar();
}
else if (current == '[')
{
int sep = SkipSep();
if (sep >= 0)
{
var longStr = ReadLongString(ref token, sep);
// Debug.Log("ReadToken string longStr : "+longStr);
token.str = longStr;
return (int)KeyWord.String;
}
return '[';
}
else if (current == '=')
{
NextChar();
if (current == '=')
return (int)KeyWord.Equal;
else
return '=';
}
else if (current == '"' || current == '\'')
{
ReadString(ref token, current);
return (int)KeyWord.String;
}
else if (current == '.')
{
NextChar();
if (CheckNext1('.'))
{
if (CheckNext1('.'))
return (int)KeyWord.Dots;
else
return (int)KeyWord.Concat;
}
else if (!IsDigit(current))
{
return '.';
}
else
{
return ReadNumeral(ref token, true);
}
}
else if (current >= (int)'0' && current <= (int)'9')
{
return ReadNumeral(ref token, false);
}
else if (current == EOZ)
{
return (int)KeyWord.EOZ;
}
else
{
if (IsAlpha(current))
{
var start_i = code_i;
do
{
NextChar();
} while(IsAlphaNum(current));
token.str = code.Substring(start_i, code_i-start_i);
return (int)TryGetReserved(token.str);
}
else
{
/* single-char tokens (+ - / ...) */
var c = current;
NextChar();
return c;
}
}
}
return 0;
}
public object Clone()
{
return this.MemberwiseClone();
}
}
private static object ParseExp(LexState ls, Type type)
{
Token t = ls.t;
switch (t.token)
{
case (int)KeyWord.String:
{
ls.MoveToNextToken();
return t.str;
}
case (int)KeyWord.Name:
{
ls.MoveToNextToken();
return t.str;
}
case (int)KeyWord.FLOAT:
{
ls.MoveToNextToken();
return t.d;
}
case (int)KeyWord.Integer:
{
ls.MoveToNextToken();
return t.i;
}
case (int)KeyWord.Nil:
{
ls.MoveToNextToken();
return null;
}
case (int)KeyWord.False:
{
ls.MoveToNextToken();
return false;
}
case (int)KeyWord.True:
{
ls.MoveToNextToken();
return true;
}
case (int)'{':
{
return ParseTableConstructor(ls, type);
}
case (int)'-':
{
ls.MoveToNextToken();
t = ls.t;
ls.MoveToNextToken();
if (t.token == (int)KeyWord.FLOAT)
return -t.d;
else if (t.token == (int)KeyWord.Integer)
return -t.i;
else
ThrowError("wrong : '-' must before a number! ls:"+ls.Dump());
return null;
}
default:
{
}
break;
}
return null;
}
private static Type TryGetRealType(LexState ls)
{
Type result = null;
if (ls.t.token == (int)'[')
{
ls.ReadAheadToken();
if (ls.lookahead.token == (int)KeyWord.String && ls.lookahead.str == "$type")
{
ls.ReadAheadToken();
ls.ReadAheadToken();
ls.ReadAheadToken();
var type_full_name = ls.lookahead.str;
if (settings != null && settings.CustomTypeDic != null && settings.CustomTypeDic.ContainsKey(type_full_name))
result = settings.CustomTypeDic[type_full_name];
else
result = Type.GetType(type_full_name);
Assert.IsNotNull(result, "cannot find type by name : "+(type_full_name));
// SceneEditorNS.PathPointInfoData
}
}
return result;
}
private static object CreateInstance(Type type)
{
if (type == typeof(string))
{
return "";
}
else if (type.IsArray)
{
var e_type = type.GetElementType();
return Array.CreateInstance(e_type, 1);
}
else
{
return System.Activator.CreateInstance(type);
}
}
private static object ParseTableConstructor(LexState ls, Type type)
{
Token t = ls.t;
if (t.token == (int)'{')
{
ls.MoveToNextToken();
object ret = null;
if (type != null)
{
Log("start table constructor for type : "+type.Name);
var old_ls_dump = ls.Dump();
var backup = ls.Clone();
var realType = TryGetRealType(ls);
// ls = backup as LexState;
ls.UpdateData(backup as LexState);
if (realType != null)
type = realType;
ret = CreateInstance(type);
Assert.IsNotNull(ret, "cannot create instance for type : "+type.Name);
}
var isOk = ParseFieldList(ls, ref ret, type);
Log("end table constructor for type : "+(type!=null?type.Name:"unknow type")+" isOk:"+isOk+" token is }"+(ls.t.token == (int)'}')+" token:"+ls.t);
if (isOk && ls.t.token == (int)'}')
{
ls.MoveToNextToken();
return ret;
}
}
else
{
Debug.LogError("wrong table constructor!"+ls.Dump());
}
return null;
}
//FieldList ::= Field {FieldSep Field} [FieldSep]
private static bool ParseFieldList(LexState ls, ref object obj, Type type)
{
Log(string.Format("obj:{0} type:{1} ls:{2}", obj, type, ls.Dump()));
int index = 0;
var isSep = false;
do
{
if (ls.t.token == (int)'}')
break;
ParseField(ls, ref obj, type, ref index);
index++;
isSep = IsFieldSep(ls.t);
if (isSep)
ls.MoveToNextToken();
} while (isSep);
return true;
}
private static bool IsFieldSep(Token t)
{
return (t.token == (int)',') || (t.token == (int)';');
}
private static Type GetTypeByMemberInfo(MemberInfo mem)
{
FieldInfo field = mem as FieldInfo;
if(field!=null)
{
return field.FieldType;
}
else
{
PropertyInfo pro = mem as PropertyInfo;
if (pro != null)
return pro.PropertyType;
}
return mem.GetType();
}
private static Type GetTypeByKeyName(object obj, Type type, string keyName)
{
if (null == keyName)
return null;
var mems = type.GetMember(keyName);
if (mems.Length == 1)
{
var mem = mems[0];
return GetTypeByMemberInfo(mem);
}
return null;
}
private static Type GetFieldTypeFromList(Type t)
{
if (t.IsGenericType)
{
var listType = t.GetGenericArguments()[0];
return listType;
}
return typeof(Nullable);
}
private static Type GetFieldTypeFromDic(Type t)
{
if (t.IsGenericType)
{
var listType = t.GetGenericArguments()[1];
return listType;
}
return typeof(Nullable);
}
private static Type GetKeyTypeFromDic(Type t)
{
if (t.IsGenericType)
{
var listType = t.GetGenericArguments()[0];
return listType;
}
return typeof(Nullable);
}
private static object ConvertToRealType(object val, Type fieldType)
{
if (val == null)
{
return null;
}
Type valType = val.GetType();
// 如果val的类型和fieldType一致,则无需转换
if (valType == fieldType)
{
return val;
}
if (fieldType.IsEnum)
return Enum.ToObject(fieldType, val);
else if (IsFloatNum(fieldType))
{
//先尝试转成更高位数的浮点型,判断实际数字是否超出范围
double doubleVal;
if (double.TryParse(val.ToString(), out doubleVal))
{
double minValue = Convert.ToDouble(fieldType.GetField("MinValue").GetValue(null));
double maxValue = Convert.ToDouble(fieldType.GetField("MaxValue").GetValue(null));
if (doubleVal < minValue || doubleVal > maxValue)
{
LogErrorStrict("Value out of range for type "+fieldType.Name+" real value:"+doubleVal);
}
return Convert.ChangeType(doubleVal, fieldType);
}
else
{
LogErrorStrict("Invalid value for type "+fieldType.Name);
return null;
}
}
else if (IsIntNumType(fieldType))
{
long longVal;
if (long.TryParse(val.ToString(), out longVal))
{
long minValue = Convert.ToInt64(fieldType.GetField("MinValue").GetValue(null));
long maxValue = Convert.ToInt64(fieldType.GetField("MaxValue").GetValue(null));
if (longVal < minValue || longVal > maxValue)
{
LogErrorStrict("Value out of range for type "+fieldType.Name+" real value:"+longVal);
}
return Convert.ChangeType(longVal, fieldType);
}
else
{
LogErrorStrict("Invalid value for type "+fieldType.Name+" real value:"+val.ToString());
return null;
}
}
else if (val.GetType() != fieldType && !val.GetType().IsSubclassOf(fieldType))
{
try {
return Convert.ChangeType(val, fieldType);
}
catch (Exception e)
{
Debug.LogError("ConvertToRealType error! val:"+val+" fieldType:"+fieldType+" e:"+e);
}
return null;
}
return val;
}
private static bool IsIntNumType(Type type)
{
return type == typeof(byte) ||
type == typeof(sbyte) ||
type == typeof(short) ||
type == typeof(ushort) ||
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(long) ||