Afternoon!
Lets say I have the array: array = {true, false, 10, "Hi", 69, true, true}
I want to remove certain entries from this array using table.remove to prevent blank space. These indicies can also be stored in a table. toRemove = {2, 3, 5}
My goal at this point is to iterate through each value in toRemove
and remove it from array
. For example, the 2
in the toRemove
table would remove the false
in the array table. However, as stated I want to use table.remove
to prevent empty spaces of nil, as these would grow in size very quick and I iterate through this table often in my game code.
I currently have something that works, but seems somewhat unorthadox. Here is what I have and a short description of what it does:
local array = {true, false, 10, "Hi", 69, true, true}
local toRemove = {1,3,4,6}
local function removeIndecies(arrayToRemoveFrom,indeciesToRemove)
local indeciesToRemove = table.sort(indeciesToRemove) --make sure indecies are in numerical order(this is needed for the method I use below
--Remove indecies from array.
for i,indexToRemove in pairs(indeciesToRemove) do
local indiciesAlreadyRemoved = i-1 --This will equate to how many indicies we have already removed.
table.remove(arratToRemoveFrom,indexToRemove-indiciesAlreadyRemoved) --We need to subtract how many indicies have already been removed here because table.remove, bumps everything after what was removed, back by one index.
end
return arrayToRemoveFrom
end
local newArray = removeIndecies(array,toRemove)
So this method works by recognizing we need to remove, say, index 3
and 4
, and then calling table.remove(table,3)
twice because that 4th index
gets bumped back to 3
after table.remove
is called once.
I was basically wondering if there was a quicker or easier way to achieve this behavior?