ArrayFunctions.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Text;
  5. namespace InABox.Core
  6. {
  7. internal static class ArrayFunctions
  8. {
  9. public const string GROUP = "Array";
  10. public static void Register()
  11. {
  12. CoreExpression.RegisterFunction("Array", "Create a new array, with the given type and length.", GROUP, new[]
  13. {
  14. "string type", "int length"
  15. }, (p, v, c) =>
  16. {
  17. var type = ConvertType(p[0].Evaluate<string>(v));
  18. var length = p[1].Evaluate<int>(v);
  19. return Array.CreateInstance(type, length);
  20. });
  21. }
  22. private static readonly Dictionary<string, Type> _types = new Dictionary<string, Type>()
  23. {
  24. { "sbyte", typeof(sbyte) },
  25. { "byte", typeof(byte) },
  26. { "short", typeof(short) },
  27. { "ushort", typeof(ushort) },
  28. { "int", typeof(int) },
  29. { "uint", typeof(uint) },
  30. { "long", typeof(long) },
  31. { "ulong", typeof(ulong) },
  32. { "float", typeof(float) },
  33. { "double", typeof(double) },
  34. { "decimal", typeof(decimal) },
  35. { "bool", typeof(bool) },
  36. { "char", typeof(char) },
  37. { "string", typeof(string) },
  38. { "TimeSpan", typeof(TimeSpan) },
  39. { "DateTime", typeof(DateTime) },
  40. };
  41. public static bool TryConvertType(string str, [NotNullWhen(true)] out Type? type)
  42. {
  43. if(_types.TryGetValue(str, out type)) return true;
  44. type = Type.GetType(str);
  45. if (type != null) return true;
  46. return false;
  47. }
  48. public static Type ConvertType(string str)
  49. {
  50. if(TryConvertType(str, out var type)) return type;
  51. throw new Exception($"Invalid type {str}");
  52. }
  53. }
  54. }