Page 1 of 1

A loop in a loop, breaking both loops

Posted: Mon May 13, 2013 8:50 pm
by Sheepolution

Code: Select all

for i=1,10 do
  	_j = 0
 	for j=1,10 do
 			print(j)
 			_j = j
 		if (j==4) then
 			
 			break
 		end
 	end
 	if (_j~=10) then
 		break
 	end
 end
This is what I have right now. It works, but I feel like I'm overdoing stuff. Something too do this easier? Is there a Lua function I'm missing maybe?

Re: A loop in a loop, breaking both loops

Posted: Mon May 13, 2013 9:27 pm
by ferdielance
Depending on your needs, the following may work more simply, or may not be practical at all.

* A: Put the whole double loop structure inside a function, and use return to get out when the time comes. (Not good in situations where having a function call every time you do the double loop is too costly)

* B: Use while for the outer loop (while counter<= value and looping == true do) and set "looping" to false in the inner loop when the time comes. This feels neater to me than having a separate break outside.

Re: A loop in a loop, breaking both loops

Posted: Mon May 13, 2013 10:30 pm
by Lafolie
Why are you doing this? Sounds like a while loop would be much more useful.

Re: A loop in a loop, breaking both loops

Posted: Tue May 14, 2013 12:15 am
by adnzzzzZ
You can always use goto to break from nested loops. I'm ready

Re: A loop in a loop, breaking both loops

Posted: Tue May 14, 2013 12:43 am
by slime
adnzzzzZ wrote:You can always use goto to break from nested loops. I'm ready
goto is only in Lua 5.2 and LuaJIT, not regular 5.1 (which is what love uses by default.)

Re: A loop in a loop, breaking both loops

Posted: Tue May 14, 2013 7:30 am
by Sheepolution
ferdielance wrote:Depending on your needs, the following may work more simply, or may not be practical at all.

* A: Put the whole double loop structure inside a function, and use return to get out when the time comes. (Not good in situations where having a function call every time you do the double loop is too costly)

* B: Use while for the outer loop (while counter<= value and looping == true do) and set "looping" to false in the inner loop when the time comes. This feels neater to me than having a separate break outside.

So something like this?

Code: Select all

i, loop = 1, true
 while (i<10 and loop) do
 	for j=1,10 do
 		print(j)
 		if (j==4) then
 			loop = false
 			break
 		end
 	end
 	i=i+1
 end
It does indeed look cleaner.
Lafolie wrote:Why are you doing this? Sounds like a while loop would be much more useful.
I'm trying to make a tile-based platformer. I need to check all tiles, and if I hit a solid one, both loops need to break.

Re: A loop in a loop, breaking both loops

Posted: Tue May 14, 2013 9:27 am
by Jasoco
There's a better way to do collision detection with a grid. A simpler way that doesn't require you to do this.

How is your level tile layout formatted? Are you using a grid like you should?