ReplComponent.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Threading;
  3. using Microsoft.CodeAnalysis.CSharp.Scripting;
  4. using Microsoft.CodeAnalysis.Scripting;
  5. namespace ET
  6. {
  7. public class ReplComponentAwakeSystem : AwakeSystem<ReplComponent>
  8. {
  9. public override void Awake(ReplComponent self)
  10. {
  11. self.ScriptOptions = ScriptOptions.Default
  12. .WithMetadataResolver(ScriptMetadataResolver.Default.WithBaseDirectory(Environment.CurrentDirectory))
  13. .AddReferences(typeof (ReplComponent).Assembly)
  14. .AddImports("System");
  15. }
  16. }
  17. public class ReplComponent: Entity
  18. {
  19. public ScriptOptions ScriptOptions;
  20. public ScriptState ScriptState;
  21. public async ETTask<bool> Run(string line, CancellationToken cancellationToken)
  22. {
  23. switch (line)
  24. {
  25. case "exit":
  26. {
  27. this.Parent.RemoveComponent<ReplComponent>();
  28. return true;
  29. }
  30. case "reset":
  31. {
  32. this.ScriptState = null;
  33. return false;
  34. }
  35. default:
  36. {
  37. try
  38. {
  39. if (this.ScriptState == null)
  40. {
  41. this.ScriptState = await CSharpScript.RunAsync(line, this.ScriptOptions, cancellationToken: cancellationToken);
  42. }
  43. else
  44. {
  45. this.ScriptState = await this.ScriptState.ContinueWithAsync(line, cancellationToken: cancellationToken);
  46. }
  47. }
  48. catch (Exception e)
  49. {
  50. Console.WriteLine(e);
  51. }
  52. return false;
  53. }
  54. }
  55. }
  56. public override void Dispose()
  57. {
  58. if (this.IsDisposed)
  59. {
  60. return;
  61. }
  62. base.Dispose();
  63. this.ScriptOptions = null;
  64. this.ScriptState = null;
  65. }
  66. }
  67. }