stillanoob
stillanoob

Reputation: 1379

Infinite for loop in Lua

Why doesn't this work in lua?

for i = 1, 100, -1 do
  print('Infinite')
end

The above loop prints nothing. From what I know from conventional languages like C/C++, the above should be an infinite loop. C++ equivalent

for (int i = 1; i <= 100; i--) 
  cout << "Infinite";

I want to know how exactly a for loop in lua works. Isn't it the same as the C++ one given above?

Edit: I don't want to know How to make an infinite loop in lua. I am more concerned here with how a for loop in lua works?

Upvotes: 2

Views: 4313

Answers (3)

Tolu Ajayi
Tolu Ajayi

Reputation: 31

A for loop in lua has the syntax below:

for init,max/min value, increment
do
   statement(s)
end

so the code below will print from 1 to 10:

for i=10,1,-1
do
   print(i)
end

To generate infinite loops in lua you might have to use while loops:

while( true )
do
   print("This loop will run forever.")
end

for more visit http://www.tutorialspoint.com/lua/lua_loops.htm

Upvotes: 0

Adam
Adam

Reputation: 81

As stated before, the for loop has three functions just like C/C++.

for i = <start>, <finish>, <increment> do 

But lua will detect that the increment will not allow the function to end and will completely ignore this loop.
To create an infinite loop, you simple use:

while true do  

In lua, putting a variable as an argument with no operator will check if the value exists/is true. If it is false/nil then it will not run. In this case, true is always true because it is constant so the loop goes forever.

while true do
     print('Infinite Loop')
end  

Upvotes: 1

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22471

for is explicitly defined in Lua to check if current value is lower than limit if step is negative. Since step -1 is negative and current value 1 is lower than limit 100 right from the start, this for performs no loops.

Upvotes: 0

Related Questions