Is there a better way to use For loops inside For loops?

This is a little embarrassing to ask considering how long I’ve been doing this but is there an easier way to write a code like this?

for i = 1,#Grids do

	for j = 1,#SelectedGrids do	

		for k = 1,#SelectedGrids[j]	do	

			if Grids[i].Name == SelectedGrids[j][k][1] then

				local SB ="SelectionBox")
				SB.Adornee = Grids[i]
				SB.Parent = Grids[i]	





I don’t think so, as the education website even does it themselves:


I don’t think so, if you need a for loop in a for loop then you need to add the for loop.

1 Like

Use table.foreach, it’s shorter

table.foreach(tbl, function(i, v)
      Do something with i(Index) and v(Value)

table.foreach is a legacy API from the pre-Lua 4.0 era; you should avoid using table.foreach if possible as it’s deprecated(!) in Lua 5.1 (the version Luau is based on) and was removed in Lua 5.2.


I know but like looking at the above code, it just doesn’t look right.

Well yeah but there aren’t any other ways, if you need to use a for loop in another for loop you gotta do it