2

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?

3

3 Answers 3

1

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  
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.