Why does Lua have no “continue” statement?

LuaServer Side ProgrammingProgramming

There’s no continue statement in Lua, and it’s not because the developers of the Lua programming language felt that it is of no use, in fact, in the official documentation they mentioned “continue was only one of a number of possible new control flow mechanisms”. This clearly shows that the developers of the Lua programming language aren’t a huge fan of the “continue” statement.

If we need to break it down the fact that why Lua developers doesn’t wanted a “continue” statement, then it comes down to two possible answers, these are −

  • They think that the “continue” statement is just another control flow mechanism and its work can be done by using other statements or a combination of other statements.
  • They wanted to make the language more lightweight.

Yes, it is true that the work that a “continue” statement does can be done using a goto statement.

Let’s explore a simple yet powerful and important code where we will make use of the goto statement that will help us to replicate the work that a continue statement does.

Example

Consider the example shown below −

 Live Demo

-- prints even numbers in [|1,10|]
for i=1,10 do
   if i % 2 == 1 then goto continue end
   print(i)
   ::continue::
end

In the above code, I used the goto keyword that will jump the control over to the ::continue:: keyword as soon as the condition i % 2 == 1 evaluates to true, and hence the loop will skip all the odd numbers and only the even numbers will be printed to the terminal.

Output

2
4
6
8
10
raja
Published on 19-Jul-2021 11:35:41
Advertisements