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?

Depends on what you are using the loops for. If you are searching for something in a table you can use table.find()

sorry for late response, will table.find() optimize it though? and if so can you show me an example of it

What’s your use of the nested loop? Since not all uses will be solved through table.find().

If you tell us about your code, we can help you find out if there are ways to optimize it. But we need more to go on than just two loop definitions.

In general, table.find won’t speed things up compared to going through a table from one end to the other, because it uses the same algorithm

A linear search algorithm is performed.

From the wiki. It might be a little faster, but you should focus on doing as little work as possible in a script instead of doing each thing a little faster.

1 Like

image

ok so thats the full script, most of it is just if statements,

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

after that the rest arent too important

If you ever heard of guard clauses, it might help you out to make your code more readable.

In a loop approach, continue is sort of usable like return as a guard clause in a loop if you want to use that.

Also just designate folders inside your model for whatever instances you want to only look at to prevent looking at the entire model.

never heard of a gaurd clause and wdym when you said

just designate folders inside your model for whatever instances you want to only look at to prevent looking at the entire model

also can that prevent the lag spike

It just prevents from having to search unnecessary objects when you can go through one folder of the stuff that you want to look for. It’s like looking through ten folders for a specific document when you could have ordered the folders by category and look in the category you want to search through.

A guard clause is a conditional statement that will prevent progression inside a function;

if clause then
    return -- stops the function
end
print(“Only if clause is not true, this is printed”)

But for a loop you can’t use return so continue kind of lets you skip the iteration in the loop instead of stopping it (an iteration is like a turn in the loop, for example a loop running 10 times has 10 iterations).

that might work for the one right above but for some of my scripts i need everything inside the folder i need all 1000 things in v and all 100 in c, however i dont want the code to run 100,000 times.