Is there a better way to do nested loops?

In the first for loop there are 1000 things it loops through then in the second there are 100 things it loops through which means it will run the code underneath both of those lines a total of 100,000 times (1000*100) which causes a lag spike in my game. is there anyway around this?

I’d move this to #help-and-feedback:scripting-support. You could also save one of the loop’s values to a table, and the loop just through one and check if it is similar to the current table value. Then, you’d not have to get all the children each time in the nested loop.

ok is there anyway i can delete this here?

You can edit the post to where it is located.

oh i already made a new post in scripting support, now theres two

Maybe try not to loop all at once, every 30 loops add a wait() for example.

then it stretches out the lag spike and is even worse

I responded in my post, tell me if it works.

I don’t think this should happen, can you show more of the loop? (like what’s happening to v and c)

sure
image just some if statements

Try doing nested if statements. I think it will help.

Also, seeing “hit” as an argument in the RemoteEvent makes me think that there is not a debounce and that’s what is causing so much lag.

Yeah. So like this

local mapChild = {}
for i, v in ipairs(workspace.Map.GetChildren()) do
table.insert(mapChild, v)
end

game.RS.ectectect:Connect(function(plr, hit)
 for i, c in ipairs(workspace.CountryValues:GetChildren()) do
  for i, v in ipairs(mapChild) do
  if v == c then print asdhahsdhasdhahsdh end
 end
end
 

end)

You can see then it doesn't have to get all the children, it already has them, which you can then check against whichever loops.

but dosnt it still loop through that table 100 times? which would still be 100*1000

It would still loop through yes, but it’d be faster in the sense that it doesn’t have to get all the children each time. You already have the children.

1 Like

i still had a lag spike at the end https://gyazo.com/4cdd3740531dd6117f0b376495927b8a

This is the same as workspace.Map.GetChildren()? I don’t see why you need extra lines of code.

Could you not just use GetDescendants, check what the parent of the descendant is and do what you want depending on what it’s parent is?

You could have a folder that holds: “Armies”, “Map”, and “CountryValues” and :GetDescendants that folder instead of :GetChildren()

Any chance you’d be interested in summarizing in English what this code is doing/supposed to do? Nesting loops like that is a last resort. Rather than trying to work backwards from what you have, it might be easier to move forward from a clear description of what you are looking to achieve.

the first if statement is finding which part in the 1000 was the one you clicked
second if statement is just seeing if you can play as the part not too important
third one finds which one in the c for loop is similar to the one in the v for loop