Control Structures & Loops

Today I want to learn Lua's control structures and loops. All languages have features that allow you to make decisions in code and loop over code.

Control Structures



The purpose of a control structure is to allow your code to choose a path in your program. In Lua, we only have the if statement. I searched online and this appears to be the case, so I guess I have to use serial (or nested ifs) or using key-value pair mapping to emulate a case/switch statement. Let's dive into the if statement. Here is an example.

Screen Shot 2021-01-26 at 8.41.27 AM


The syntax is straightforward. Remember that ~= represents "not equal" in Lua. I keep wanting to type !=, even though I've used other languages with this token. The block of code (Lua chunk) is delimited by then and end.

As in other languages you can also use an else. For non-terminating else statements, Lua uses the keyword elseif.


Screen Shot 2021-01-26 at 8.41.01 AM


So, without a case/switch statement, you can use this style instead. You can also nest if statements.

Screen Shot 2021-01-26 at 8.46.26 AM


Loops



A chunk of code that is repeated is usually in a loop. Lua has several types which should be familiar to me. Again, I"m teaching myself, and not really writing a tutorial, but these posts may be useful to others.

while loops work the way I expect. Here is my test program. The test is done at the top of the loop, and the loop may not execute depending on the condition. As a reminder, the .. operator is used to concatenate.

Screen Shot 2021-01-26 at 8.54.31 AM


Lua also has a break statement which lets you leave the current loop, and a return statement can exit the current loop and function.

The next loop is the repeat until. This loop executes at least once and the test is performed at the end of the chunk.

Screen Shot 2021-01-26 at 9.00.51 AM

Even though this is a Lua chunk, it is not terminated by an end until.

Finally, Lua has a for loop. The syntax reminds me of the FORTRAN do loop.

Screen Shot 2021-01-26 at 9.05.31 AM

The three parameters are the standard initializer, limit, and iterator. The iterator (3d number) is optional and can be negative.

If my test program is confusing, here is the output.


Screen Shot 2021-01-26 at 9.06.42 AM

Loops can be nested as in other languages. Here's is the meaningless test I wrote.

Screen Shot 2021-01-26 at 9.13.14 AM

And some of the output.

Screen Shot 2021-01-26 at 9.14.29 AM


There is, apparently, one other kind of for loop. I'm guessing it's related to iterating over objects of some sort, but I haven't learned about them yet.


That covers Lua's if statement, the one control structure, and the three loop forms.



This site does not track your information.