File size: 1,847 Bytes
18a519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Collections;

namespace Unity.VisualScripting
{
    /// <summary>
    /// Loops as long as a given condition is true.
    /// </summary>
    [UnitTitle("While Loop")]
    [UnitCategory("Control")]
    [UnitOrder(11)]
    public class While : LoopUnit
    {
        /// <summary>
        /// The condition to check at each iteration to determine whether the loop should continue.
        /// </summary>
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput condition { get; private set; }

        protected override void Definition()
        {
            base.Definition();

            condition = ValueInput<bool>(nameof(condition));

            Requirement(condition, enter);
        }

        private int Start(Flow flow)
        {
            return flow.EnterLoop();
        }

        private bool CanMoveNext(Flow flow)
        {
            return flow.GetValue<bool>(condition);
        }

        protected override ControlOutput Loop(Flow flow)
        {
            var loop = Start(flow);

            var stack = flow.PreserveStack();

            while (flow.LoopIsNotBroken(loop) && CanMoveNext(flow))
            {
                flow.Invoke(body);

                flow.RestoreStack(stack);
            }

            flow.DisposePreservedStack(stack);

            flow.ExitLoop(loop);

            return exit;
        }

        protected override IEnumerator LoopCoroutine(Flow flow)
        {
            var loop = Start(flow);

            var stack = flow.PreserveStack();

            while (flow.LoopIsNotBroken(loop) && CanMoveNext(flow))
            {
                yield return body;

                flow.RestoreStack(stack);
            }

            flow.DisposePreservedStack(stack);

            flow.ExitLoop(loop);

            yield return exit;
        }
    }
}