First steps with Lua - LoopsDeutsch


You are here:LuaLoops



Loops

For-Loop

Parameter for the For-command:

  1. Initial value
  2. End value
  3. Inkrement


Rail-Diagramm forstat1

Test-Programm loop_for_1.lua
for variable = 0, 10, 2 do
	print ( variable )
end
The Result:
0
2
4
6
8
10

Test-Programm loop_for_2.lua
for variable = 0, 1, .5 do
	print ( variable )
end
The Result:
0
0.5
1
The loop value doesn't need to be a in whole numbers.

Test-Programm loop_for_2.lua
for variable = 0, 1, .5 do
	print ( variable )
end
The Result:
0
0.5
1
Decrement works also.

There is a special variant of the for-command for tables.

While-Loop


Rail-Diagramm while
Test-Programm loop_while_1.lua
i = 1
while i  <= 5 do
	 print (i)
	 i = i + 1
end
The Result:
1
2
3
4
5

Repeat-loop


Rail-Diagramm repeat
Test-Programm loop_repeat_1.lua
i = 1
repeat
	 print (i)
	 i = i + 1
until i > 5
The Result:
1
2
3
4
5

Abortion

You can stop the loop with Break.

Test-Programm loop_break_1.lua
for variable = 1, -1, -.5 do
	if variable == 0 then
		print "Null erreicht"
		break
	end
	print ( variable )
end
The Result:
1
0.5
Null erreicht