- Lua Tutorial
- Lua - Home
- Lua Basics Tutorial
- Lua - Overview
- Lua - Environment
- Lua - Basic Syntax
- Lua - Variables
- Lua - Data Types
- Lua - Operators
- Lua - Loops
- Lua - Decision Making
- Lua - Functions
- Lua - Strings
- Lua - Arrays
- Lua - Iterators
- Lua - Tables
- Lua - Modules
- Lua - Metatables
- Lua - Coroutines
- Lua - File I/O
- Lua - Error Handling
- Lua Advanced
- Lua - Debugging
- Lua - Garbage Collection
- Lua - Object Oriented
- Lua - Web Programming
- Lua - Database Access
- Lua - Game Programing
- Lua Useful Resources
- Lua - Quick Guide
- Lua - Useful Resources
- Lua - Discussion
Lua - nested Loops
Lua programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in Lua is as follows −
for init,max/min value, increment do for init,max/min value, increment do statement(s) end statement(s) end
The syntax for a nested while loop statement in Lua programming language is as follows −
while(condition) do while(condition) do statement(s) end statement(s) end
The syntax for a nested repeat...until loop statement in Lua programming language is as follows −
repeat statement(s) repeat statement(s) until( condition ) until( condition )
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop −
j = 2 for i = 2,10 do for j = 2,(i/j) , 2 do if(not(i%j)) then break end if(j > (i/j))then print("Value of i is",i) end end end
When you build and run the above code, it produces the following result.
Value of i is 8 Value of i is 9 Value of i is 10
lua_loops.htm
Advertisements