-
Notifications
You must be signed in to change notification settings - Fork 76
/
LuaLibraries.cs
1886 lines (1610 loc) · 55.1 KB
/
LuaLibraries.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
#region -- copyright --
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
#pragma warning disable IDE1006 // Naming Styles
namespace Neo.IronLua
{
#region -- String Manipulation ----------------------------------------------------
/// <summary>Reimplements methods of the string package.</summary>
public static class LuaLibraryString
{
private static bool translateRegEx = true;
private static void NormalizeStringArguments(string s, int i, int j, out int offset, out int len)
{
if (i == 0)
i = 1;
if (i < 0) // Suffix mode
{
offset = s.Length + i;
if (offset < 0)
offset = 0;
len = (j < 0 ? s.Length + j + 1 : j) - offset;
}
else // Prefix mode
{
offset = i - 1;
if (j < 0)
j = s.Length + j + 1;
len = j - offset;
}
// correct the length
if (offset + len > s.Length)
len = s.Length - offset;
} // proc NormalizeStringArguments
private static Tuple<string, bool[]> TranslateRegularExpression(string regEx)
{
if (!translateRegEx)
return new Tuple<string, bool[]>(regEx, null);
var sb = new StringBuilder();
var escapeCode = false;
var inCharList = false;
var captures = new List<bool>
{
false // full result
};
for (var i = 0; i < regEx.Length; i++)
{
var c = regEx[i];
if (escapeCode)
{
if (c == '%')
{
sb.Append('%');
escapeCode = false;
}
else
{
#region -- char groups --
switch (c)
{
case 'a': // all letters
sb.Append("\\p{L}");
break;
case 'A': // all Non letters
sb.Append("\\P{L}");
break;
case 's': // all space characters
sb.Append("\\s");
break;
case 'S': // all NON space characters
sb.Append("\\S");
break;
case 'd': // all digits
sb.Append("\\d");
break;
case 'D': // all NON digits
sb.Append("\\D");
break;
case 'w': // all alphanumeric characters
sb.Append("\\w");
break;
case 'W': // all NON alphanumeric characters
sb.Append("\\W");
break;
case 'c': // all control characters
sb.Append("\\p{C}");
break;
case 'C': // all NON control characters
sb.Append("[\\P{C}]");
break;
case 'g': // all printable characters except space
sb.Append("[^\\p{C}\\s]");
break;
case 'G': // all NON printable characters including space
sb.Append("[\\p{C}\\s]");
break;
case 'p': // all punctuation characters
sb.Append("\\p{P}");
break;
case 'P': // all NON punctuation characters
sb.Append("\\P{P}");
break;
case 'l': // all lowercase letters
sb.Append("\\p{Ll}");
break;
case 'L': // all NON lowercase letters
sb.Append("\\P{Ll}");
break;
case 'u': // all uppercase letters
sb.Append("\\p{Lu}");
break;
case 'U': // all NON uppercase letters
sb.Append("\\P{Lu}");
break;
case 'x': // all hexadecimal digits
sb.Append("[0-9A-Fa-f]");
break;
case 'X': // all NON hexadecimal digits
sb.Append("[^0-9A-Fa-f]");
break;
case 'b': // github #12
if (i < regEx.Length - 2)
{
var c1 = regEx[i + 1];
var c2 = regEx[i + 2];
//Example for %b()
//(\((?>(?<n>\()|(?<-n>\))|(?:[^\(\)]*))*\)(?(n)(?!)))
//Example for %bab
//(a(?>(?<n>a)|(?<-n>b)|(?:[^ab]*))*b(?(n)(?!)))
sb.Append("(");
sb.Append(Regex.Escape(c1.ToString()));
sb.Append("(?>(?<n>");
sb.Append(Regex.Escape(c1.ToString()));
sb.Append(")|(?<-n>");
sb.Append(Regex.Escape(c2.ToString()));
sb.Append(")|(?:[^");
sb.Append(Regex.Escape(c1.ToString()));
sb.Append(Regex.Escape(c2.ToString()));
sb.Append("]*))*");
sb.Append(Regex.Escape(c2.ToString()));
sb.Append("(?(n)(?!)))");
i += 2;
}
else
throw new ArgumentOutOfRangeException();
break;
default:
sb.Append('\\');
sb.Append(c);
break;
}
#endregion
escapeCode = false;
}
}
else if (c == '%')
{
escapeCode = true;
}
else if (c == '\\')
{
sb.Append("\\\\");
}
else if (inCharList)
{
if (c == ']')
inCharList = false;
sb.Append(c);
}
else if (c == '-')
{
sb.Append("*?");
}
else if (c == '[')
{
sb.Append('[');
inCharList = true;
}
else if (c == '^' && !inCharList)
{
sb.Append("\\G");
}
else if (c == '(')
{
sb.Append('(');
captures.Add(i + 1 < regEx.Length && regEx[i + 1] == ')');
}
else
sb.Append(c);
}
return new Tuple<string, bool[]>(sb.ToString(), captures.ToArray());
} // func TranslateRegularExpression
/// <summary>Implamentation of http://www.lua.org/manual/5.3/manual.html#pdf-string.byte </summary>
/// <param name="s"></param>
/// <param name="i"></param>
/// <param name="j"></param>
/// <returns></returns>
public static LuaResult @byte(this string s, int? i = null, int? j = null)
{
if (!i.HasValue)
i = 1;
if (!j.HasValue)
j = i;
if (String.IsNullOrEmpty(s) || i == 0)
return LuaResult.Empty;
NormalizeStringArguments(s, i.Value, j.Value, out var ofs, out var len);
if (len <= 0)
return LuaResult.Empty;
var r = new object[len];
for (var a = 0; a < len; a++)
r[a] = (int)s[ofs + a];
return r;
} // func byte
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.char </summary>
/// <param name="chars"></param>
/// <returns></returns>
public static string @char(params int[] chars)
{
if (chars == null)
return String.Empty;
var sb = new StringBuilder(chars.Length);
for (int i = 0; i < chars.Length; i++)
sb.Append((char)chars[i]);
return sb.ToString();
} // func char
/// <summary>Not implemented</summary>
/// <param name="dlg"></param>
/// <returns></returns>
public static string dump(Delegate dlg)
=> throw new NotImplementedException();
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.find </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <param name="init"></param>
/// <param name="plain"></param>
/// <returns></returns>
public static LuaResult find(this string s, string pattern, int init = 1, bool plain = false)
{
if (String.IsNullOrEmpty(s))
{
return String.IsNullOrEmpty(pattern) && init == 1
? new LuaResult(1)
: LuaResult.Empty;
}
if (String.IsNullOrEmpty(pattern))
return LuaResult.Empty;
// correct the init parameter
if (init < 0)
init = s.Length + init + 1;
if (init <= 0)
init = 1;
if (plain) // plain pattern
{
var index = s.IndexOf(pattern, init - 1);
return index == -1 ?
null :
new LuaResult(index + 1, index + pattern.Length);
}
else
{
// translate the regular expression
var tranlatedPattern = TranslateRegularExpression(pattern).Item1;
var r = new Regex(tranlatedPattern);
var m = r.Match(s, init - 1);
if (m.Success)
{
var result = new object[m.Groups.Count + 1]; // first group is all, so add 2 - 1
// offset of the match
result[0] = m.Index + 1;
result[1] = m.Index + m.Length;
// copy the groups
for (var i = 1; i < m.Groups.Count; i++)
result[i + 1] = m.Groups[i].Value;
return result;
}
else
return LuaResult.Empty;
}
} // func find
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.format </summary>
/// <param name="formatstring"></param>
/// <param name="args"></param>
/// <returns></returns>
public static string format(this string formatstring, params object[] args)
=> AT.MIN.Tools.sprintf(formatstring, args);
private static LuaResult MatchEnum(object s, object current)
{
var e = (System.Collections.IEnumerator)s;
// return value
if (e.MoveNext())
{
var m = (Match)e.Current;
return MatchResult(m, null);
}
else
return LuaResult.Empty;
} // func matchEnum
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.gmatch </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static LuaResult gmatch(this string s, string pattern)
{
System.Collections.IEnumerator e;
// f,s,v
if (String.IsNullOrEmpty(s)
|| String.IsNullOrEmpty(pattern))
{
e = Enumerable.Empty<object>().GetEnumerator();
}
else
{
// translate the regular expression
pattern = TranslateRegularExpression(pattern).Item1;
// Find Matches
e = Regex.Matches(s, pattern).GetEnumerator();
}
return new LuaResult(new Func<object, object, LuaResult>(MatchEnum), e, e);
} // func gmatch
#region -- class GSubMatchEvaluator -------------------------------------------
#region -- class GSubMatchEvaluator -------------------------------------------
private abstract class GSubMatchEvaluator
{
private int matchCount = 0;
public string MatchEvaluator(Match m)
{
matchCount++;
return MatchEvaluatorImpl(m);
} // func MatchEvaluator
protected abstract string MatchEvaluatorImpl(Match m);
public int MatchCount => matchCount;
} // class GSubMatchEvaluator
#endregion
#region -- class GSubLuaTableMatchEvaluator -----------------------------------
private sealed class GSubLuaTableMatchEvaluator : GSubMatchEvaluator
{
private readonly LuaTable t;
private readonly bool ignoreCase;
public GSubLuaTableMatchEvaluator(LuaTable t)
{
this.t = t ?? throw new ArgumentNullException(nameof(t));
ignoreCase = (bool)Lua.RtConvertValue(t.GetMemberValue("__IgnoreCase"), typeof(bool));
} // ctor
protected override string MatchEvaluatorImpl(Match m)
=> (string)Lua.RtConvertValue(t.GetMemberValue(m.Groups[1].Value, ignoreCase), typeof(string));
} // class GSubLuaTableMatchEvaluator
#endregion
#region -- class GSubFunctionMatchEvaluator -----------------------------------
private sealed class GSubFunctionMatchEvaluator : GSubMatchEvaluator
{
private CallSite callSite = null;
private readonly object funcCall;
public GSubFunctionMatchEvaluator(object funcCall)
{
this.funcCall = funcCall ?? throw new ArgumentNullException(nameof(funcCall));
} // ctor
private void UpdateCallSite(CallInfo callInfo, CallSite callSite)
{
this.callSite = callSite;
} // proc UpdateCallSite
protected override string MatchEvaluatorImpl(Match m)
{
var args = new string[m.Groups.Count - 1];
for (var i = 1; i < m.Groups.Count; i++)
args[i - 1] = m.Groups[i].Value;
return (string)Lua.RtConvertValue(Lua.RtInvokeSite(callSite, callInfo => new Lua.LuaInvokeBinder(null, callInfo), UpdateCallSite, funcCall, args), typeof(string));
} // func MatchEvaluator
} // class GSubLuaTableMatchEvaluator
#endregion
#region -- class GSubStringMatchEvaluator -------------------------------------
private sealed class GSubStringMatchEvaluator : GSubMatchEvaluator
{
private readonly object[] replaces;
public GSubStringMatchEvaluator(string repl)
{
var lst = new List<object>();
var i = 0;
var ofs = 0;
while (i < repl.Length)
{
if (repl[i] == '%')
{
if (++i >= repl.Length)
break;
if (repl[i] == '%') // Parse a number (0-9)
{
Add(lst, repl, ofs, i);
ofs = i + 1;
}
else if (repl[i] >= '0' && repl[i] <= '9') // Add what we find until now
{
Add(lst, repl, ofs, i - 1);
lst.Add(repl[i] - '0');
ofs = i + 1;
}
}
i++;
}
// Add the rest
Add(lst, repl, ofs, i);
replaces = lst.ToArray();
} // ctor
private static void Add(List<object> lst, string repl, int offset, int current)
{
var length = current - offset;
if (length == 0)
return;
lst.Add(repl.Substring(offset, length));
} // proc Add
protected override string MatchEvaluatorImpl(Match m)
{
var result = new string[replaces.Length];
for (var i = 0; i < result.Length; i++)
{
if (replaces[i] is string s)
result[i] = s;
else if (replaces[i] is int idx)
{
if (idx == 0)
result[i] = m.Value;
else if (idx <= m.Groups.Count)
result[i] = m.Groups[idx].Value;
else
result[i] = String.Empty;
}
else
result[i] = String.Empty;
}
return String.Concat(result);
} // func MatchEvaluator
} // class GSubLuaTableMatchEvaluator
#endregion
#endregion
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.gsub </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <param name="repl"></param>
/// <param name="n"></param>
/// <returns></returns>
public static LuaResult gsub(this string s, string pattern, object repl, int n)
{
var regex = new Regex(TranslateRegularExpression(pattern).Item1);
if (n <= 0)
n = Int32.MaxValue;
GSubMatchEvaluator matchEvaluator;
if (repl is LuaTable table)
matchEvaluator = new GSubLuaTableMatchEvaluator(table);
else if (repl is Delegate || repl is ILuaMethod)
matchEvaluator = new GSubFunctionMatchEvaluator(repl);
else
matchEvaluator = new GSubStringMatchEvaluator((string)Lua.RtConvertValue(repl, typeof(string)));
var r = regex.Replace(s, matchEvaluator.MatchEvaluator, n);
return new LuaResult(r, matchEvaluator.MatchCount);
} // func gsub
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.len </summary>
/// <param name="s"></param>
/// <returns></returns>
public static int len(this string s)
=> s == null ? 0 : s.Length;
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.lower </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string lower(this string s)
{
if (String.IsNullOrEmpty(s))
return s;
return s.ToLower();
} // func lower
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.match </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <param name="init"></param>
/// <returns></returns>
public static LuaResult match(this string s, string pattern, int init = 1)
{
if (String.IsNullOrEmpty(s))
return LuaResult.Empty;
if (String.IsNullOrEmpty(pattern))
return LuaResult.Empty;
// correct the init parameter
if (init < 0)
init = s.Length + init + 1;
if (init <= 0)
init = 1;
// translate the regular expression
var trans = TranslateRegularExpression(pattern);
var r = new Regex(trans.Item1);
return MatchResult(r.Match(s, init - 1), trans.Item2);
} // func match
private static LuaResult MatchResult(Match m, bool[] indexReturn)
{
if (m.Success)
{
if (m.Groups.Count > 1) // the expression uses groups, return the groups
{
var result = new object[m.Groups.Count - 1];
for (var i = 1; i < m.Groups.Count; i++)
result[i - 1] = MatchCaptureValue(i, m.Groups[i], indexReturn);
return result;
}
else // no groups, return the captures
{
var result = new object[m.Captures.Count];
for (var i = 0; i < m.Captures.Count; i++)
result[i] = MatchCaptureValue(i, m.Captures[i], indexReturn);
return result;
}
}
else
return LuaResult.Empty;
} // func MatchResult
private static object MatchCaptureValue(int i, Capture capture, bool[] indexReturn)
=> indexReturn != null && i < indexReturn.Length && indexReturn[i]
? (object)(capture.Index + 1)
: capture.Value;
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.rep </summary>
/// <param name="s"></param>
/// <param name="n"></param>
/// <param name="sep"></param>
/// <returns></returns>
public static string rep(this string s, int n, string sep = "")
{
if (n == 0)
return String.Empty;
return String.Join(sep, Enumerable.Repeat(s, n));
} // func rep
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.reverse </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string reverse(this string s)
{
if (String.IsNullOrEmpty(s) || s.Length == 1)
return s;
var a = s.ToCharArray();
Array.Reverse(a);
return new string(a);
} // func reverse
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.sub </summary>
/// <param name="s"></param>
/// <param name="i"></param>
/// <param name="j"></param>
/// <returns></returns>
public static string sub(this string s, int i, int j = -1)
{
if (String.IsNullOrEmpty(s) || j == 0)
return String.Empty;
NormalizeStringArguments(s, i, j, out var ofs, out var len);
// return the string
return len <= 0
? String.Empty
: s.Substring(ofs, len);
} // func sub
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-string.upper </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string upper(this string s)
{
if (String.IsNullOrEmpty(s))
return s;
return s.ToUpper();
} // func lower
// todo: pack
// todo: packsize
// todo: unpack
/// <summary>Set this member to <c>false</c> to use native (.net) regex syntax.</summary>
public static bool __TranslateRegEx { get { return translateRegEx; } set { translateRegEx = value; } }
} // class LuaLibraryString
#endregion
#region -- Mathematical Functions -------------------------------------------------
/// <summary>Reimplements methods of the math package.</summary>
public static class LuaLibraryMath
{
private static Random rand = null;
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.abs </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double abs(double x)
=> Math.Abs(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.acos </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double acos(double x)
=> Math.Acos(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.asin </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double asin(double x)
=> Math.Asin(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.atan </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double atan(double x)
=> Math.Atan(x);
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.atan2 </summary>
/// <param name="y"></param>
/// <param name="x"></param>
/// <returns></returns>
public static double atan2(double y, double x)
=> Math.Atan2(y, x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.ceil </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double ceil(double x)
=> Math.Ceiling(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.cos </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double cos(double x)
=> Math.Cos(x);
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.cosh </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double cosh(double x)
=> Math.Cosh(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.deg </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double deg(double x)
=> x * 180.0 / Math.PI;
/// <summary>Implementation of </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double exp(double x)
=> Math.Exp(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.floor </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double floor(double x)
=> Math.Floor(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.fmod </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static double fmod(double x, double y)
=> x % y;
/// <summary>Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero, http://www.lua.org/manual/5.2/manual.html#pdf-math.frexp).</summary>
/// <param name="x"></param>
/// <returns></returns>
public static LuaResult frexp(double x)
{
var exponent = (x == 0.0) ? 0 : (int)(1 + Math.Log(Math.Abs(x), 2));
var mantissa = x * (Math.Pow(2, -exponent));
return new LuaResult(mantissa, exponent);
} // func frexp
/// <summary>The value HUGE_VAL, a value larger than or equal to any other numerical value (http://www.lua.org/manual/5.3/manual.html#pdf-math.huge).</summary>
public static double huge => Double.MaxValue;
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.ldexp </summary>
/// <param name="m"></param>
/// <param name="e"></param>
/// <returns></returns>
public static double ldexp(double m, int e)
=> m * Math.Pow(2, e); // Returns m2e (e should be an integer).
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.log </summary>
/// <param name="x"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double log(double x, double b = Math.E)
=> Math.Log(x, b);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.max </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double max(double[] x)
{
if (x == null || x.Length == 0)
throw new LuaRuntimeException(Properties.Resources.rsNumberExpected, 1, true);
var r = Double.MinValue;
for (var i = 0; i < x.Length; i++)
{
if (r < x[i])
r = x[i];
}
return r;
} // func max
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.min </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double min(double[] x)
{
if (x == null || x.Length == 0)
throw new LuaRuntimeException(Properties.Resources.rsNumberExpected, 1, true);
var r = Double.MaxValue;
for (var i = 0; i < x.Length; i++)
{
if (r > x[i])
r = x[i];
}
return r;
} // func min
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.modf </summary>
/// <param name="x"></param>
/// <returns></returns>
public static LuaResult modf(double x)
{
if (x < 0)
{
var y = Math.Ceiling(x);
return new LuaResult(y, y - x);
}
else
{
var y = Math.Floor(x);
return new LuaResult(y, x - y);
}
} // func modf
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.pow </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static double pow(double x, double y)
=> Math.Pow(x, y);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.rad </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double rad(double x)
=> x * Math.PI / 180.0;
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.random </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static object random(object m = null, object n = null)
{
if (rand == null)
rand = new Random();
if (m == null && n == null)
return rand.NextDouble();
else if (m != null && n == null)
return rand.Next(1, Convert.ToInt32(m));
else
return rand.Next(Convert.ToInt32(m), Convert.ToInt32(n));
} // func random
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.randomseed </summary>
/// <param name="x"></param>
public static void randomseed(object x)
{
int seed;
if (x == null)
seed = Environment.TickCount;
else
{
var tc = LuaEmit.GetTypeCode(x.GetType());
if (tc >= LuaEmitTypeCode.Byte && tc <= LuaEmitTypeCode.Decimal)
seed = Convert.ToInt32(x);
else if (tc == LuaEmitTypeCode.DateTime)
seed = unchecked((int)((DateTime)x).ToFileTime());
else
seed = x.GetHashCode();
}
rand = new Random(seed);
} // proc randomseed
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.sin </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double sin(double x)
=> Math.Sin(x);
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.sinh </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double sinh(double x)
=> Math.Sinh(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.sqrt </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double sqrt(double x)
=> Math.Sqrt(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.tan </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double tan(double x)
=> Math.Tan(x);
/// <summary>Implementation of http://www.lua.org/manual/5.2/manual.html#pdf-math.tanh </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double tanh(double x)
=> Math.Tanh(x);
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.type </summary>
/// <param name="x"></param>
/// <returns></returns>
public static string type(object x)
{
if (x == null)
return null;
else
{
switch (LuaEmit.GetTypeCode(x.GetType()))
{
case LuaEmitTypeCode.Byte:
case LuaEmitTypeCode.SByte:
case LuaEmitTypeCode.Int16:
case LuaEmitTypeCode.UInt16:
case LuaEmitTypeCode.Int32:
case LuaEmitTypeCode.UInt32:
case LuaEmitTypeCode.Int64:
case LuaEmitTypeCode.UInt64:
return "integer";
case LuaEmitTypeCode.Double:
case LuaEmitTypeCode.Single:
case LuaEmitTypeCode.Decimal:
return "float";
default:
return null;
}
}
} // func type
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.tointeger </summary>
/// <param name="x"></param>
/// <returns></returns>
public static object tointeger(object x)
{
try
{
return (long)Lua.RtConvertValue(x, typeof(long));
}
catch
{
return null;
}
} // func tointeger
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.ult </summary>
/// <param name="m"></param>
/// <param name="n"></param>
/// <returns></returns>
public static bool ult(long m, long n)
=> m < n;
/// <summary>Implementation of http://www.lua.org/manual/5.3/manual.html#pdf-math.pi </summary>
public static double pi => Math.PI;
/// <summary>Maps Math.E</summary>
public static double e => Math.E;