I was wrapping up some stuff about a type of production line thing, and I’ve noticed a very big problem. It’s the fact that the script only loops through HALF of the table.
For example, if I looped through 5 times, it would only do it 3 times (rounded up from 2.5)
I’ve looked at a post relating to this, but I had some trouble understanding it and adapting it into my code. Apparently, modifying tables inside of a for loop would create some issues, and I’d like some help to fully understand how this issue works and how to solve it.
pairs is useful when you want to iterate through all types of keys, not just numerical ones.
For example, say we have the table
local someTable = {
Bob = 123,
Tom = 245,
}
pairs will give you both values, such that:
for index, value in pairs(someTable) do
print(index, value)
end
--Would output:
--Bob 123
--Tom 245
ipairs is just like pairs, except it only works with numerical indexes, such as 1, 2, 3, and will stop if there is a nil value.
For example:
local someTable = {4,5,6,9}
for index, value in ipairs(someTable) do
print(index, value)
end
--Would output:
--1 4
--2 5
--3 6
--4 9
If you’re looking to remove certain elements from a table, doing so while in iteration with pairs isn’t the solution you’re looking for.
I’m not sure when you’re removing all elements from your queue, so I can only give the generic info above. For more detailed help, I’d require more explanation as of what you’re trying to do.
Essentially, I’m trying to make some kind of production line, where something is queued up in a table, then a loop (started by the first production command) loops through all of that, and does its thing.
I’m just searching for some kind of new way to avoid the issues that removing values in a pairs loop does
The table of obj’s has Instances inside of it, allowing for the script to just do a quick :Clone() and bring it up
The easiest solution is just using a generic for loop, but iterating backwards so when you remove elements it doesn’t cause any issues.
What that would look like:
local queue = {1,2,3,4,5} --Some queue
for i = #queue, 1, -1 do --Iterate backwards
local value = queue[i] --If you want to use the value at this index
if someCondition then --Ideally some check for if we want to remove the item
table.remove(queue, i) --Remove the item
end
end
Since table.remove shifts the order of the table, iterating forwards causes us to skip values:
--Say we have 1,2,3 and we are looking at index 1
--We remove 1, leaving us with 2,3. However, because we iterate fowards we are now on index 2
--Index 2 is now 3, so we don't check 2, causing the skip
When you iterate backwards, you remove this issue.
The loop will run once, unless you run it constantly using something like RunService.Stepped. Without seeing more of your code, I can’t really help much more than that.