|
| 1 | +using JetBrains.Annotations; |
| 2 | +using MEC; |
| 3 | +using SER.Code.ContextSystem.BaseContexts; |
| 4 | +using SER.Code.ContextSystem.Interfaces; |
| 5 | +using SER.Code.ContextSystem.Structures; |
| 6 | +using SER.Code.Exceptions; |
| 7 | +using SER.Code.Extensions; |
| 8 | +using SER.Code.Helpers; |
| 9 | +using SER.Code.Helpers.ResultSystem; |
| 10 | +using SER.Code.TokenSystem.Tokens; |
| 11 | + |
| 12 | +namespace SER.Code.ContextSystem.Contexts.Control; |
| 13 | + |
| 14 | +[UsedImplicitly] |
| 15 | +public class WaitUntilKeyword : YieldingContext, IKeywordContext |
| 16 | +{ |
| 17 | + public virtual string KeywordName => "wait_until"; |
| 18 | + |
| 19 | + public virtual string Description => "Halts execution of the script until a condition is met."; |
| 20 | + |
| 21 | + public virtual string[] Arguments => ["<condition...>"]; |
| 22 | + |
| 23 | + public virtual string? Example => |
| 24 | + """ |
| 25 | + # wait until there are no players on the server |
| 26 | + wait_until {AmountOf @all} is 0 |
| 27 | + """; |
| 28 | + |
| 29 | + public override string FriendlyName => $"'{KeywordName}' keyword"; |
| 30 | + |
| 31 | + protected readonly List<BaseToken> Tokens = []; |
| 32 | + private NumericExpressionReslover.CompiledExpression _expression; |
| 33 | + |
| 34 | + public override TryAddTokenRes TryAddToken(BaseToken token) |
| 35 | + { |
| 36 | + Tokens.Add(token); |
| 37 | + return TryAddTokenRes.Continue(); |
| 38 | + } |
| 39 | + |
| 40 | + public override Result VerifyCurrentState() |
| 41 | + { |
| 42 | + if (Tokens.Count == 0) |
| 43 | + { |
| 44 | + return $"The condition was not provided for the '{KeywordName}' keyword."; |
| 45 | + } |
| 46 | + |
| 47 | + if (NumericExpressionReslover.CompileExpression(Tokens.ToArray()) |
| 48 | + .HasErrored(out var error, out var cond)) |
| 49 | + { |
| 50 | + return error; |
| 51 | + } |
| 52 | + |
| 53 | + _expression = cond; |
| 54 | + return true; |
| 55 | + } |
| 56 | + |
| 57 | + protected override IEnumerator<float> Execute() |
| 58 | + { |
| 59 | + while (!GetConditionResult()) |
| 60 | + { |
| 61 | + yield return Timing.WaitForOneFrame; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private bool GetConditionResult() |
| 66 | + { |
| 67 | + if (_expression.Evaluate().HasErrored(out var error, out var objResult)) |
| 68 | + { |
| 69 | + throw new ScriptRuntimeError(this, error); |
| 70 | + } |
| 71 | + |
| 72 | + if (objResult is not bool result) |
| 73 | + { |
| 74 | + throw new ScriptRuntimeError( |
| 75 | + this, |
| 76 | + $"'{KeywordName}' condition must evaluate to a boolean value, but received {objResult.FriendlyTypeName()}" |
| 77 | + ); |
| 78 | + } |
| 79 | + |
| 80 | + return result; |
| 81 | + } |
| 82 | +} |
0 commit comments