Control Structures & Loops
01/26/21 08:19 Filed in: Lua
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.
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.
So, without a case/switch statement, you can use this style instead. You can also nest if statements.
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.
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.
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.
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.
Loops can be nested as in other languages. Here's is the meaningless test I wrote.
And some of the output.
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.