官术网_书友最值得收藏!

Time for action – Something

  1. As an example of what NOT to do, let's take this code.
    var int Int1;
    
    function PostBeginPlay()
    {
        Int1 = 5;
    
        While(Int1 > 0)
        {
            Int1 = 5;
        }
    }
  2. When we run the game with this code, it will crash.
    Time for action – Something

    It is EXTREMELY IMPORTANT to always make sure the "while" condition will be met to avoid infinite loop crashes.

  3. Let's take a look at the right way to use it:
    var int Int1;
    
    function PostBeginPlay()
    {
        While(Int1 < 5)
        {
            'log("Int1" @ Int1);
            Int1++;
        }
    }

    In this case, Int1 will keep incrementing until it reaches 5, and the While loop will exit.

  4. We could also use a statement called break to exit the loop:
    var int Int1;
    
    function PostBeginPlay()
    {
        While(Int1 < 5)
        {
            'log("Int1" @ Int1);
            Int1++;
            if(Int1 == 3)
                break;
        }
    }

    In this case, the loop will exit when Int1 reaches 3 instead of continuing until it hits 5.

  5. Another statement we can use is called continue. Instead of exiting the loop completely, it just skips to the next cycle.
    var int Int1;
    
    function PostBeginPlay()
    {
        While(Int1 < 5)
        {
            'log("Int1" @ Int1);
            Int1++;
    
            if(Int1 == 3)
                continue;
    
            'log("This will not log if Int1 is 3");
        }
    }

In this case, the loop will keep going until Int1 hits 5, but when it's equal to 3 the continue statement will cause it to skip the rest of the code for that loop and move on to the next loop.

What just happened?

Using while statements can be handy when you don't know the number of loops you'll need beforehand, or if it would change during play. You always have to make sure the loop will be able to finish though; crashing the game is a very real concern when using while loops.

Do until

Do until is basically another way of using a while loop, and it carries the same concerns of infinite loops. An example of how to write one would be this:

do
{
    'log("Int1" @ Int1);
    Int1++;
} until (Int1 > 5);

Switch

Switch is used as a more complex form of the if/else statement, and in certain cases it can lead to cleaner code. It also has the ability to execute more than one statement for a condition.

主站蜘蛛池模板: 海林市| 奉化市| 平顶山市| 平利县| 漯河市| 威远县| 肥乡县| 怀来县| 利辛县| 和龙市| 永清县| 大同县| 邹城市| 紫金县| 邻水| 凤冈县| 宾川县| 连州市| 岐山县| 温宿县| 金平| 温宿县| 万宁市| 汕头市| 望奎县| 安平县| 鲁甸县| 建宁县| 乌鲁木齐市| 青神县| 郯城县| 探索| 夏邑县| 龙门县| 文安县| 洮南市| 凭祥市| 玛纳斯县| 瑞丽市| 廊坊市| 绍兴市|