-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathDynValue.cs
More file actions
974 lines (851 loc) · 26.7 KB
/
DynValue.cs
File metadata and controls
974 lines (851 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace MoonSharp.Interpreter
{
/// <summary>
/// A class representing a value in a Lua/MoonSharp script.
/// </summary>
public sealed class DynValue
{
static int s_RefIDCounter = 0;
private int m_RefID = ++s_RefIDCounter;
private int m_HashCode = -1;
private bool m_ReadOnly;
private double m_Number;
private object m_Object;
private DataType m_Type;
/// <summary>
/// Gets a unique reference identifier. This is guaranteed to be unique only for dynvalues created in a single thread as it's not thread-safe.
/// </summary>
public int ReferenceID { get { return m_RefID; } }
/// <summary>
/// Gets the type of the value.
/// </summary>
public DataType Type { get { return m_Type; } }
/// <summary>
/// Gets the function (valid only if the <see cref="Type"/> is <see cref="DataType.Function"/>)
/// </summary>
public Closure Function { get { return m_Object as Closure; } }
/// <summary>
/// Gets the numeric value (valid only if the <see cref="Type"/> is <see cref="DataType.Number"/>)
/// </summary>
public double Number { get { return m_Number; } }
/// <summary>
/// Gets the values in the tuple (valid only if the <see cref="Type"/> is Tuple).
/// This field is currently also used to hold arguments in values whose <see cref="Type"/> is <see cref="DataType.TailCallRequest"/>.
/// </summary>
public DynValue[] Tuple { get { return m_Object as DynValue[]; } }
/// <summary>
/// Gets the coroutine handle. (valid only if the <see cref="Type"/> is Thread).
/// </summary>
public Coroutine Coroutine { get { return m_Object as Coroutine; } }
/// <summary>
/// Gets the table (valid only if the <see cref="Type"/> is <see cref="DataType.Table"/>)
/// </summary>
public Table Table { get { return m_Object as Table; } }
/// <summary>
/// Gets the boolean value (valid only if the <see cref="Type"/> is <see cref="DataType.Boolean"/>)
/// </summary>
public bool Boolean { get { return Number != 0; } }
/// <summary>
/// Gets the string value (valid only if the <see cref="Type"/> is <see cref="DataType.String"/>)
/// </summary>
public string String { get { return m_Object as string; } }
/// <summary>
/// Gets the CLR callback (valid only if the <see cref="Type"/> is <see cref="DataType.ClrFunction"/>)
/// </summary>
public CallbackFunction Callback { get { return m_Object as CallbackFunction; } }
/// <summary>
/// Gets the tail call data.
/// </summary>
public TailCallData TailCallData { get { return m_Object as TailCallData; } }
/// <summary>
/// Gets the yield request data.
/// </summary>
public YieldRequest YieldRequest { get { return m_Object as YieldRequest; } }
/// <summary>
/// Gets the tail call data.
/// </summary>
public UserData UserData { get { return m_Object as UserData; } }
/// <summary>
/// Returns true if this instance is write protected.
/// </summary>
public bool ReadOnly { get { return m_ReadOnly; } }
/// <summary>
/// Creates a new writable value initialized to Nil.
/// </summary>
public static DynValue NewNil()
{
return new DynValue();
}
/// <summary>
/// Creates a new writable value initialized to the specified boolean.
/// </summary>
public static DynValue NewBoolean(bool v)
{
return new DynValue()
{
m_Number = v ? 1 : 0,
m_Type = DataType.Boolean,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified number.
/// </summary>
public static DynValue NewNumber(double num)
{
return new DynValue()
{
m_Number = num,
m_Type = DataType.Number,
m_HashCode = -1,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified string.
/// </summary>
public static DynValue NewString(string str)
{
return new DynValue()
{
m_Object = str,
m_Type = DataType.String,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified StringBuilder.
/// </summary>
public static DynValue NewString(StringBuilder sb)
{
return new DynValue()
{
m_Object = sb.ToString(),
m_Type = DataType.String,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified string using String.Format like syntax
/// </summary>
public static DynValue NewString(string format, params object[] args)
{
return new DynValue()
{
m_Object = string.Format(format, args),
m_Type = DataType.String,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified coroutine.
/// Internal use only, for external use, see Script.CoroutineCreate
/// </summary>
/// <param name="coroutine">The coroutine object.</param>
/// <returns></returns>
public static DynValue NewCoroutine(Coroutine coroutine)
{
return new DynValue()
{
m_Object = coroutine,
m_Type = DataType.Thread
};
}
/// <summary>
/// Creates a new writable value initialized to the specified closure (function).
/// </summary>
public static DynValue NewClosure(Closure function)
{
return new DynValue()
{
m_Object = function,
m_Type = DataType.Function,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified CLR callback.
/// </summary>
public static DynValue NewCallback(Func<ScriptExecutionContext, CallbackArguments, DynValue> callBack, string name = null)
{
return new DynValue()
{
m_Object = new CallbackFunction(callBack, name),
m_Type = DataType.ClrFunction,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified CLR callback.
/// See also CallbackFunction.FromDelegate and CallbackFunction.FromMethodInfo factory methods.
/// </summary>
public static DynValue NewCallback(CallbackFunction function)
{
return new DynValue()
{
m_Object = function,
m_Type = DataType.ClrFunction,
};
}
/// <summary>
/// Creates a new writable value initialized to the specified table.
/// </summary>
public static DynValue NewTable(Table table)
{
return new DynValue()
{
m_Object = table,
m_Type = DataType.Table,
};
}
/// <summary>
/// Creates a new writable value initialized to an empty prime table (a
/// prime table is a table made only of numbers, strings, booleans and other
/// prime tables).
/// </summary>
public static DynValue NewPrimeTable()
{
return NewTable(new Table(null));
}
/// <summary>
/// Creates a new writable value initialized to an empty table.
/// </summary>
public static DynValue NewTable(Script script)
{
return NewTable(new Table(script));
}
/// <summary>
/// Creates a new writable value initialized to with array contents.
/// </summary>
public static DynValue NewTable(Script script, params DynValue[] arrayValues)
{
return NewTable(new Table(script, arrayValues));
}
/// <summary>
/// Creates a new request for a tail call. This is the preferred way to execute Lua/MoonSharp code from a callback,
/// although it's not always possible to use it. When a function (callback or script closure) returns a
/// TailCallRequest, the bytecode processor immediately executes the function contained in the request.
/// By executing script in this way, a callback function ensures it's not on the stack anymore and thus a number
/// of functionality (state savings, coroutines, etc) keeps working at full power.
/// </summary>
/// <param name="tailFn">The function to be called.</param>
/// <param name="args">The arguments.</param>
/// <returns></returns>
public static DynValue NewTailCallReq(DynValue tailFn, params DynValue[] args)
{
return new DynValue()
{
m_Object = new TailCallData()
{
Args = args,
Function = tailFn,
},
m_Type = DataType.TailCallRequest,
};
}
/// <summary>
/// Creates a new request for a tail call. This is the preferred way to execute Lua/MoonSharp code from a callback,
/// although it's not always possible to use it. When a function (callback or script closure) returns a
/// TailCallRequest, the bytecode processor immediately executes the function contained in the request.
/// By executing script in this way, a callback function ensures it's not on the stack anymore and thus a number
/// of functionality (state savings, coroutines, etc) keeps working at full power.
/// </summary>
/// <param name="tailCallData">The data for the tail call.</param>
/// <returns></returns>
public static DynValue NewTailCallReq(TailCallData tailCallData)
{
return new DynValue()
{
m_Object = tailCallData,
m_Type = DataType.TailCallRequest,
};
}
/// <summary>
/// Creates a new request for a yield of the current coroutine.
/// </summary>
/// <param name="args">The yield argumenst.</param>
/// <returns></returns>
public static DynValue NewYieldReq(DynValue[] args)
{
return new DynValue()
{
m_Object = new YieldRequest() { ReturnValues = args },
m_Type = DataType.YieldRequest,
};
}
/// <summary>
/// Creates a new request for a yield of the current coroutine.
/// </summary>
/// <param name="args">The yield argumenst.</param>
/// <returns></returns>
internal static DynValue NewForcedYieldReq()
{
return new DynValue()
{
m_Object = new YieldRequest() { Forced = true },
m_Type = DataType.YieldRequest,
};
}
/// <summary>
/// Creates a new tuple initialized to the specified values.
/// </summary>
public static DynValue NewTuple(params DynValue[] values)
{
if (values.Length == 0)
return DynValue.NewNil();
if (values.Length == 1)
return values[0];
return new DynValue()
{
m_Object = values,
m_Type = DataType.Tuple,
};
}
/// <summary>
/// Creates a new tuple initialized to the specified values - which can be potentially other tuples
/// </summary>
public static DynValue NewTupleNested(params DynValue[] values)
{
if (!values.Any(v => v.Type == DataType.Tuple))
return NewTuple(values);
if (values.Length == 1)
return values[0];
List<DynValue> vals = new List<DynValue>();
foreach (var v in values)
{
if (v.Type == DataType.Tuple)
vals.AddRange(v.Tuple);
else
vals.Add(v);
}
return new DynValue()
{
m_Object = vals.ToArray(),
m_Type = DataType.Tuple,
};
}
/// <summary>
/// Creates a new userdata value
/// </summary>
public static DynValue NewUserData(UserData userData)
{
return new DynValue()
{
m_Object = userData,
m_Type = DataType.UserData,
};
}
/// <summary>
/// Returns this value as readonly - eventually cloning it in the process if it isn't readonly to start with.
/// </summary>
public DynValue AsReadOnly()
{
if (ReadOnly)
return this;
else
{
return Clone(true);
}
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public DynValue Clone()
{
return Clone(this.ReadOnly);
}
/// <summary>
/// Clones this instance, overriding the "readonly" status.
/// </summary>
/// <param name="readOnly">if set to <c>true</c> the new instance is set as readonly, or writeable otherwise.</param>
/// <returns></returns>
public DynValue Clone(bool readOnly)
{
DynValue v = new DynValue();
v.m_Object = this.m_Object;
v.m_Number = this.m_Number;
v.m_HashCode = this.m_HashCode;
v.m_Type = this.m_Type;
v.m_ReadOnly = readOnly;
return v;
}
/// <summary>
/// Clones this instance, returning a writable copy.
/// </summary>
/// <exception cref="System.ArgumentException">Can't clone Symbol values</exception>
public DynValue CloneAsWritable()
{
return Clone(false);
}
/// <summary>
/// A preinitialized, readonly instance, equaling Void
/// </summary>
public static DynValue Void { get; private set; }
/// <summary>
/// A preinitialized, readonly instance, equaling Nil
/// </summary>
public static DynValue Nil { get; private set; }
/// <summary>
/// A preinitialized, readonly instance, equaling True
/// </summary>
public static DynValue True { get; private set; }
/// <summary>
/// A preinitialized, readonly instance, equaling False
/// </summary>
public static DynValue False { get; private set; }
static DynValue()
{
Nil = new DynValue() { m_Type = DataType.Nil }.AsReadOnly();
Void = new DynValue() { m_Type = DataType.Void }.AsReadOnly();
True = DynValue.NewBoolean(true).AsReadOnly();
False = DynValue.NewBoolean(false).AsReadOnly();
}
/// <summary>
/// Returns a string which is what it's expected to be output by the print function applied to this value.
/// </summary>
public string ToPrintString()
{
if (this.m_Object != null && this.m_Object is RefIdObject)
{
RefIdObject refid = (RefIdObject)m_Object;
string typeString = this.Type.ToLuaTypeString();
if (m_Object is UserData)
{
UserData ud = (UserData)m_Object;
string str = ud.Descriptor.AsString(ud.Object);
if (str != null)
return str;
}
return refid.FormatTypeString(typeString);
}
switch (Type)
{
case DataType.String:
return String;
case DataType.Tuple:
return string.Join("\t", Tuple.Select(t => t.ToPrintString()).ToArray());
case DataType.TailCallRequest:
return "(TailCallRequest -- INTERNAL!)";
case DataType.YieldRequest:
return "(YieldRequest -- INTERNAL!)";
default:
return ToString();
}
}
/// <summary>
/// Returns a string which is what it's expected to be output by debuggers.
/// </summary>
public string ToDebugPrintString()
{
if (this.m_Object != null && this.m_Object is RefIdObject)
{
RefIdObject refid = (RefIdObject)m_Object;
string typeString = this.Type.ToLuaTypeString();
if (m_Object is UserData)
{
UserData ud = (UserData)m_Object;
string str = ud.Descriptor.AsString(ud.Object);
if (str != null)
return str;
}
return refid.FormatTypeString(typeString);
}
switch (Type)
{
case DataType.Tuple:
return string.Join("\t", Tuple.Select(t => t.ToPrintString()).ToArray());
case DataType.TailCallRequest:
return "(TailCallRequest)";
case DataType.YieldRequest:
return "(YieldRequest)";
default:
return ToString();
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
switch (Type)
{
case DataType.Void:
return "void";
case DataType.Nil:
return "nil";
case DataType.Boolean:
return Boolean.ToString().ToLower();
case DataType.Number:
return Number.ToString(CultureInfo.InvariantCulture);
case DataType.String:
return "\"" + String + "\"";
case DataType.Function:
return string.Format("(Function {0:X8})", Function.EntryPointByteCodeLocation);
case DataType.ClrFunction:
return string.Format("(Function CLR)", Function);
case DataType.Table:
return "(Table)";
case DataType.Tuple:
return string.Join(", ", Tuple.Select(t => t.ToString()).ToArray());
case DataType.TailCallRequest:
return "Tail:(" + string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()) + ")";
case DataType.UserData:
return "(UserData)";
case DataType.Thread:
return string.Format("(Coroutine {0:X8})", this.Coroutine.ReferenceID);
default:
return "(???)";
}
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
if (m_HashCode != -1)
return m_HashCode;
int baseValue = ((int)(Type)) << 27;
switch (Type)
{
case DataType.Void:
case DataType.Nil:
m_HashCode = 0;
break;
case DataType.Boolean:
m_HashCode = Boolean ? 1 : 2;
break;
case DataType.Number:
m_HashCode = baseValue ^ Number.GetHashCode();
break;
case DataType.String:
m_HashCode = baseValue ^ String.GetHashCode();
break;
case DataType.Function:
m_HashCode = baseValue ^ Function.GetHashCode();
break;
case DataType.ClrFunction:
m_HashCode = baseValue ^ Callback.GetHashCode();
break;
case DataType.Table:
m_HashCode = baseValue ^ Table.GetHashCode();
break;
case DataType.Tuple:
case DataType.TailCallRequest:
m_HashCode = baseValue ^ Tuple.GetHashCode();
break;
case DataType.UserData:
case DataType.Thread:
default:
m_HashCode = 999;
break;
}
return m_HashCode;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
DynValue other = obj as DynValue;
if (other == null) return false;
if ((other.Type == DataType.Nil && this.Type == DataType.Void)
|| (other.Type == DataType.Void && this.Type == DataType.Nil))
return true;
if (other.Type != this.Type) return false;
switch (Type)
{
case DataType.Void:
case DataType.Nil:
return true;
case DataType.Boolean:
return Boolean == other.Boolean;
case DataType.Number:
return Number == other.Number;
case DataType.String:
return String == other.String;
case DataType.Function:
return Function == other.Function;
case DataType.ClrFunction:
return Callback == other.Callback;
case DataType.Table:
return Table == other.Table;
case DataType.Tuple:
case DataType.TailCallRequest:
return Tuple == other.Tuple;
case DataType.Thread:
return Coroutine == other.Coroutine;
case DataType.UserData:
{
UserData ud1 = this.UserData;
UserData ud2 = other.UserData;
if (ud1 == null || ud2 == null)
return false;
if (ud1.Descriptor != ud2.Descriptor)
return false;
if (ud1.Object == null && ud2.Object == null)
return true;
if (ud1.Object != null && ud2.Object != null)
return ud1.Object.Equals(ud2.Object);
return false;
}
default:
return object.ReferenceEquals(this, other);
}
}
/// <summary>
/// Casts this DynValue to string, using coercion if the type is number.
/// </summary>
/// <returns>The string representation, or null if not number, not string.</returns>
public string CastToString()
{
DynValue rv = ToScalar();
if (rv.Type == DataType.Number)
{
return rv.Number.ToString(CultureInfo.InvariantCulture);
}
else if (rv.Type == DataType.String)
{
return rv.String;
}
return null;
}
/// <summary>
/// Casts this DynValue to a double, using coercion if the type is string.
/// </summary>
/// <returns>The string representation, or null if not number, not string or non-convertible-string.</returns>
public double? CastToNumber()
{
DynValue rv = ToScalar();
if (rv.Type == DataType.Number)
{
return rv.Number;
}
else if (rv.Type == DataType.String)
{
double num;
if (double.TryParse(rv.String, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
return num;
}
return null;
}
/// <summary>
/// Casts this DynValue to a bool
/// </summary>
/// <returns>False if value is false or nil, true otherwise.</returns>
public bool CastToBool()
{
DynValue rv = ToScalar();
if (rv.Type == DataType.Boolean)
return rv.Boolean;
else return (rv.Type != DataType.Nil && rv.Type != DataType.Void);
}
/// <summary>
/// Returns this DynValue as an instance of <see cref="IScriptPrivateResource"/>, if possible,
/// null otherwise
/// </summary>
/// <returns>False if value is false or nil, true otherwise.</returns>
public IScriptPrivateResource GetAsPrivateResource()
{
return m_Object as IScriptPrivateResource;
}
/// <summary>
/// Converts a tuple to a scalar value. If it's already a scalar value, this function returns "this".
/// </summary>
public DynValue ToScalar()
{
if (Type != DataType.Tuple)
return this;
if (Tuple.Length == 0)
return DynValue.Void;
return Tuple[0].ToScalar();
}
/// <summary>
/// Performs an assignment, overwriting the value with the specified one.
/// </summary>
/// <param name="value">The value.</param>
/// <exception cref="ScriptRuntimeException">If the value is readonly.</exception>
public void Assign(DynValue value)
{
if (this.ReadOnly)
throw new ScriptRuntimeException("Assigning on r-value");
this.m_Number = value.m_Number;
this.m_Object = value.m_Object;
this.m_Type = value.Type;
this.m_HashCode = -1;
}
/// <summary>
/// Gets the length of a string or table value.
/// </summary>
/// <returns></returns>
/// <exception cref="ScriptRuntimeException">Value is not a table or string.</exception>
public DynValue GetLength()
{
if (this.Type == DataType.Table)
return DynValue.NewNumber(this.Table.Length);
if (this.Type == DataType.String)
return DynValue.NewNumber(this.String.Length);
throw new ScriptRuntimeException("Can't get length of type {0}", this.Type);
}
/// <summary>
/// Determines whether this instance is nil or void
/// </summary>
public bool IsNil()
{
return this.Type == DataType.Nil || this.Type == DataType.Void;
}
/// <summary>
/// Determines whether this instance is not nil or void
/// </summary>
public bool IsNotNil()
{
return this.Type != DataType.Nil && this.Type != DataType.Void;
}
/// <summary>
/// Determines whether this instance is void
/// </summary>
public bool IsVoid()
{
return this.Type == DataType.Void;
}
/// <summary>
/// Determines whether this instance is not void
/// </summary>
public bool IsNotVoid()
{
return this.Type != DataType.Void;
}
/// <summary>
/// Determines whether is nil, void or NaN (and thus unsuitable for using as a table key).
/// </summary>
public bool IsNilOrNan()
{
return (this.Type == DataType.Nil) || (this.Type == DataType.Void) || (this.Type == DataType.Number && double.IsNaN(this.Number));
}
/// <summary>
/// Changes the numeric value of a number DynValue.
/// </summary>
internal void AssignNumber(double num)
{
if (this.ReadOnly)
throw new InternalErrorException(null, "Writing on r-value");
if (this.Type != DataType.Number)
throw new InternalErrorException("Can't assign number to type {0}", this.Type);
this.m_Number = num;
}
/// <summary>
/// Creates a new DynValue from a CLR object
/// </summary>
/// <param name="script">The script.</param>
/// <param name="obj">The object.</param>
/// <returns></returns>
public static DynValue FromObject(Script script, object obj)
{
return MoonSharp.Interpreter.Interop.Converters.ClrToScriptConversions.ObjectToDynValue(script, obj);
}
/// <summary>
/// Converts this MoonSharp DynValue to a CLR object.
/// </summary>
public object ToObject()
{
return MoonSharp.Interpreter.Interop.Converters.ScriptToClrConversions.DynValueToObject(this);
}
/// <summary>
/// Converts this MoonSharp DynValue to a CLR object of the specified type.
/// </summary>
public object ToObject(Type desiredType)
{
//Contract.Requires(desiredType != null);
return MoonSharp.Interpreter.Interop.Converters.ScriptToClrConversions.DynValueToObjectOfType(this, desiredType, null, false);
}
/// <summary>
/// Converts this MoonSharp DynValue to a CLR object of the specified type.
/// </summary>
public T ToObject<T>()
{
T myObject = (T)ToObject(typeof(T));
if (myObject == null) {
return default(T);
}
return myObject;
}
#if HASDYNAMIC
/// <summary>
/// Converts this MoonSharp DynValue to a CLR object, marked as dynamic
/// </summary>
public dynamic ToDynamic()
{
return MoonSharp.Interpreter.Interop.Converters.ScriptToClrConversions.DynValueToObject(this);
}
#endif
/// <summary>
/// Checks the type of this value corresponds to the desired type. A propert ScriptRuntimeException is thrown
/// if the value is not of the specified type or - considering the TypeValidationFlags - is not convertible
/// to the specified type.
/// </summary>
/// <param name="funcName">Name of the function requesting the value, for error message purposes.</param>
/// <param name="desiredType">The desired data type.</param>
/// <param name="argNum">The argument number, for error message purposes.</param>
/// <param name="flags">The TypeValidationFlags.</param>
/// <returns></returns>
/// <exception cref="ScriptRuntimeException">Thrown
/// if the value is not of the specified type or - considering the TypeValidationFlags - is not convertible
/// to the specified type.</exception>
public DynValue CheckType(string funcName, DataType desiredType, int argNum = -1, TypeValidationFlags flags = TypeValidationFlags.Default)
{
if (this.Type == desiredType)
return this;
bool allowNil = ((int)(flags & TypeValidationFlags.AllowNil) != 0);
if (allowNil && this.IsNil())
return this;
bool autoConvert = ((int)(flags & TypeValidationFlags.AutoConvert) != 0);
if (autoConvert)
{
if (desiredType == DataType.Boolean)
return DynValue.NewBoolean(this.CastToBool());
if (desiredType == DataType.Number)
{
double? v = this.CastToNumber();
if (v.HasValue)
return DynValue.NewNumber(v.Value);
}
if (desiredType == DataType.String)
{
string v = this.CastToString();
if (v != null)
return DynValue.NewString(v);
}
}
if (this.IsVoid())
throw ScriptRuntimeException.BadArgumentNoValue(argNum, funcName, desiredType);
throw ScriptRuntimeException.BadArgument(argNum, funcName, desiredType, this.Type, allowNil);
}
/// <summary>
/// Checks if the type is a specific userdata type, and returns it or throws.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="funcName">Name of the function.</param>
/// <param name="argNum">The argument number.</param>
/// <param name="flags">The flags.</param>
/// <returns></returns>
public T CheckUserDataType<T>(string funcName, int argNum = -1, TypeValidationFlags flags = TypeValidationFlags.Default)
{
DynValue v = this.CheckType(funcName, DataType.UserData, argNum, flags);
bool allowNil = ((int)(flags & TypeValidationFlags.AllowNil) != 0);
if (v.IsNil())
return default(T);
object o = v.UserData.Object;
if (o != null && o is T)
return (T)o;
throw ScriptRuntimeException.BadArgumentUserData(argNum, funcName, typeof(T), o, allowNil);
}
}
}