Functions.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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] = (Func<EraRuntime, StackFrame, IList<Parameter>, Value>)Delegate.CreateDelegate(typeof(Func<EraRuntime, StackFrame, IList<Parameter>, Value>), method);
  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("__INLINEIF")]
  38. public static Value InlineIf(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  39. {
  40. // For syntax like \@THIRD_PERSON?Third Person#Second Person\@
  41. if (parameters.Count != 3)
  42. throw new EraRuntimeException("Invalid amount of parameters");
  43. return parameters[0].Value
  44. ? parameters[1].Value
  45. : parameters[2].Value;
  46. }
  47. [Function("TOSTR")]
  48. public static Value ToStr(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  49. {
  50. if (parameters.Count == 1)
  51. return parameters[0].ToString();
  52. if (parameters.Count == 2)
  53. return ((int)parameters[0].Value).ToString(parameters[1].Value.String);
  54. throw new EraRuntimeException("Invalid amount of parameters");
  55. }
  56. private static Random _random = new Random();
  57. [Function("RAND")]
  58. public static Value Rand(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
  59. {
  60. return _random.Next((int)parameters[0].Value.Real, (int)parameters[1].Value.Real);
  61. }
  62. }
  63. }