Control structures
The Lua control structures are quite similar to the C++ control structures. Try to compare them with their C++ counterparts as you learn about them.
For the code shown in this section, you can put them in another Lua script file named 2-controls.lua
, and import it with dofile
in the Lua interpreter. You can put each example in a separate function so that you can test the code with different parameters. By now, you should be comfortable using the Lua interpreter, so we will not show how to do it in the rest of this chapter.
We will first explore how to do conditional branching in Lua, and then we will venture into loops.
if then else
The Lua if
control structure is similar to the C++ one. However, you do not need the parentheses around the test condition, and you do not use the curly brackets. Instead, you will need the then
keyword and the end
keyword to delimit the code branches, for example:
if a < 0 then a = 0 end if a > 0 then return a else...