Loops in LuaĪs you can tell from the sample code, although there are different implementations, loops all basically work toward the same goal. It's the terse way of writing while 1 = 1 or something similarly eternally true. The condition while true is always satisfied because true is always true. Here's an example infinite loop, again with a safety catch built in for convenience: n = 0 The simple condition used in these cases is one that is obviously always satisfied. There's no way of knowing how long your user intends to use the application, so the program runs infinitely until the user selects Quit. Graphical applications use what are technically infinite loops to keep the application window open. Infinite loops actually do have their uses. The and operator has a different effect, but I leave that to you to explore. The flawed logic is the or operator, which permits this loop to continue both when foo is greater than 3 and when bar is less than 1. You can safely run this code, but it does mimic an accidental infinite loop. If a loop is set to run until foo > 3 or bar 3 or bar < 1 ) do For instance, at the start of this article, I posed a logic puzzle. This is often a bug caused by bad logic or an unexpected state in your program. Suppose you've taken up gardening and you want to track what's left to harvest: mytable = Īn infinite loop has a condition that can never be satisfied, so it runs infinitely. Lua also has a repeat until loop construct that's essentially a while loop with a "catch" statement. Run the code to watch the zombies vanish: $ lua. There are also logical operators, which mean the same as they mean in English and can be incorporated into conditions to further describe the state you want to check for:įoo > 3: Is the variable foo is greater than 3? The foo must be 4 or more to satisfy this condition.įoo >= 3: Is foo greater than or equal to 3? The foo must be 3 or more to satisfy this condition. Those are known as relational operators because they prompt an investigation of how two values relate to one another. Because of their flexibility, I cover for loops in a separate article.Ī condition is defined by an expression using an operator, which is a fancy term for symbols you may recognize from math classes. This article covers the while and repeat until loops. Different languages provide different controls, and in Lua there's the while loop, for loop, and repeat until loop. Welcome to the communityĬontrol structures are an important feature of programming languages because they enable you to direct the flow of the program based on conditions that are often established dynamically as the program is running.
0 Comments
Leave a Reply. |