1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- namespace NTERA.Engine.Runtime.Base
- {
- public static class Functions
- {
- private class FunctionAttribute : Attribute
- {
- public string Name { get; }
- public FunctionAttribute(string name)
- {
- Name = name;
- }
- }
- public static Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>> StaticFunctions { get; } = _getFunctions();
- private static Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>> _getFunctions()
- {
- var output = new Dictionary<string, Func<EraRuntime, StackFrame, IList<Parameter>, Value>>();
- foreach (MethodInfo method in typeof(Functions).GetMethods(BindingFlags.Public | BindingFlags.Static))
- {
- var function = method.GetCustomAttribute<FunctionAttribute>();
- if (function != null)
- output[function.Name] = (runtime, set, parameters) => (Value)method.Invoke(null, new object[] { runtime, set, parameters });
- }
- return output;
- }
- [Function("__FORMAT")]
- public static Value Format(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
- {
- if (parameters.Count == 1)
- return parameters[0].Value.String;
- if (parameters.Count >= 3)
- throw new NotImplementedException("Advanced formatting hasn't been implemented yet");
- return parameters[0].Value.String.PadLeft((int)parameters[1].Value.Real);
- }
- [Function("TOSTR")]
- public static Value ToStr(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
- {
- if (parameters.Count == 1)
- return parameters[0].ToString();
- if (parameters.Count == 2)
- return ((int)parameters[0].Value).ToString(parameters[1].Value.String);
- throw new EraRuntimeException("Invalid amount of parameters");
- }
- private static Random _random = new Random();
- [Function("RAND")]
- public static Value Rand(EraRuntime runtime, StackFrame context, IList<Parameter> parameters)
- {
- return _random.Next((int)parameters[0].Value.Real, (int)parameters[1].Value.Real);
- }
- }
- }
|