A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Runtime.InteropServices;
  5. namespace TechbloxModdingAPI.Commands
  6. {
  7. internal static class CustomCommands
  8. {
  9. public struct CommandData
  10. {
  11. public string Name;
  12. public string Description;
  13. public Delegate Action;
  14. }
  15. private static Dictionary<string, CommandData> _commands = new Dictionary<string, CommandData>();
  16. public static void Register(string name, Delegate action, string desc)
  17. {
  18. _commands.Add(name, new CommandData
  19. {
  20. Name = name,
  21. Description = desc,
  22. Action = action
  23. });
  24. }
  25. public static void Call(string name, params object[] args)
  26. {
  27. if (_commands.TryGetValue(name, out var command))
  28. {
  29. var paramz = command.Action.Method.GetParameters();
  30. if (paramz.Length > args.Length)
  31. throw new CommandParameterMissingException(
  32. $"This command requires {paramz.Length} arguments, {args.Length} given");
  33. for (var index = 0; index < paramz.Length; index++)
  34. {
  35. args[index] = Convert.ChangeType(args[index], paramz[index].ParameterType);
  36. }
  37. command.Action.DynamicInvoke(args);
  38. }
  39. else
  40. throw new CommandNotFoundException($"Command {name} does not exist!");
  41. }
  42. public static void Unregister(string name)
  43. {
  44. _commands.Remove(name);
  45. }
  46. public static bool Exists(string name) => _commands.ContainsKey(name);
  47. public static ReadOnlyDictionary<string, CommandData> GetAllCommandData() =>
  48. new ReadOnlyDictionary<string, CommandData>(_commands);
  49. }
  50. }