ReplComponent.cs 2.2 KB

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