Functions.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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<Value>, Value>> StaticFunctions { get; } = _getFunctions();
  17. private static Dictionary<string, Func<EraRuntime, StackFrame, IList<Value>, Value>> _getFunctions()
  18. {
  19. var output = new Dictionary<string, Func<EraRuntime, StackFrame, IList<Value>, 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<Value> parameters)
  30. {
  31. if (parameters.Count == 1)
  32. return parameters[0].String;
  33. throw new NotImplementedException("Advanced formatting hasn't been implemented yet");
  34. }
  35. [Function("TOSTR")]
  36. public static Value ToStr(EraRuntime runtime, StackFrame context, IList<Value> parameters)
  37. {
  38. if (parameters.Count == 1)
  39. return parameters[0].ToString();
  40. if (parameters.Count == 2)
  41. return ((int)parameters[0]).ToString(parameters[1].String);
  42. throw new EraRuntimeException("Invalid amount of parameters");
  43. }
  44. private static Random _random = new Random();
  45. [Function("RAND")]
  46. public static Value Rand(EraRuntime runtime, StackFrame context, IList<Value> parameters)
  47. {
  48. return _random.Next((int)parameters[0].Real, (int)parameters[1].Real);
  49. }
  50. }
  51. }