Functions.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace NTERA.Engine.Runtime.Base
  5. {
  6. public static class Functions
  7. {
  8. private class FunctionAttribute : Attribute
  9. {
  10. public string Name { get; }
  11. public FunctionAttribute(string name)
  12. {
  13. Name = name;
  14. }
  15. }
  16. public static Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>> StaticFunctions { get; } = _getFunctions();
  17. private static Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>> _getFunctions()
  18. {
  19. var output = new Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>>();
  20. foreach (MethodInfo method in typeof(Functions).GetMethods(BindingFlags.Public | BindingFlags.Static))
  21. {
  22. var function = method.GetCustomAttribute<FunctionAttribute>();
  23. if (function != null)
  24. output[function.Name] = (runtime, set, parameters) => (Value)method.Invoke(null, new object[] { runtime, set, parameters });
  25. }
  26. return output;
  27. }
  28. [Function("__FORMAT")]
  29. public static Value Format(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  30. {
  31. if (parameters.Count == 1)
  32. return parameters[0].Value.String;
  33. if (parameters.Count >= 3)
  34. throw new NotImplementedException("Advanced formatting hasn't been implemented yet");
  35. return parameters[0].Value.String.PadLeft((int)parameters[1].Value.Real);
  36. }
  37. [Function("TOSTR")]
  38. public static Value ToStr(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  39. {
  40. if (parameters.Count == 1)
  41. return parameters[0].ToString();
  42. if (parameters.Count == 2)
  43. return ((int)parameters[0].Value).ToString(parameters[1].Value.String);
  44. throw new EraRuntimeException("Invalid amount of parameters");
  45. }
  46. private static Random _random = new Random();
  47. [Function("RAND")]
  48. public static Value Rand(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  49. {
  50. return _random.Next((int)parameters[0].Value.Real, (int)parameters[1].Value.Real);
  51. }
  52. }
  53. }