How should I loop through and remove indices in a table?

for i,v in ipairs(tableA) do
 table.remove(tableA, i)
end

doesn’t work, and I just figured out why. The indices of all other vales shift as an index is removed.

My question is, what do I replace it with?

for i,v in ipairs(tableA) do
 table.remove(tableA, 1)
end

or

for i,v in ipairs(tableA) do
 tableA[i] = nil
end

My problem with the second one is that the table will increase in size forever as I keep inserting into it, and my problem with the first one is that it seems a bit stupid.

But if you think the first one’s alright then I will use that.

I decided to use the second one, but I no longer insert into the table, instead I index it and add the value.

table.clear(tableA)
tableA = {}
for i in pairs(tableA) do
    tableA[i] = nil
end

:man_shrugging:

In addition to what @Expertcoderz said ,

local tableA = {"Hey","World"}

--Clearing

table.clear(tableA)
print(tableA["Hey"]) --> nil

tableA = {} 
print(tableA["Hey"]) --> nil


--Removing

table.remove(tableA,tableA[1]) -- or tableA["Hey"] = nil
print(tableA["Hey"]) --> nil


for index in pairs(tableA) do
	tableA[index] = nil
	print(tableA[1]) --> nil
end


Umm, your tableA is an array so to get the string "Hey" stored inside it you’ll have to do tableA[1] since the index of value "Hey" is 1.

Essentially, what your tableA looks like is this:

{[1] = "Hey", [2] = "World"}

Also,

table.remove takes in the numerical index (position) of the item to remove as the second argument, not the value itself.

So it should be:

table.remove(tableA, 1)

Just to expand on this, use table.clear(tableA) instead of tableA = {} if you intend to use tableA again, as the former approach caches the memory allocated to the array part of the table allowing for it to be reused more efficiently.

task.wait(3)
local t1 = os.clock()
local tables1 = {1, 2, 3}
tables1 = {}
tables1 = {4, 5, 6}
local t2 = os.clock()
local tables2 = {1, 2, 3}
table.clear(tables2)
tables2 = {4, 5, 6}
local t3 = os.clock()
print(t2 - t1)
print(t3 - t2)

image

It may be hard to visualize these numbers but the second option is almost twice as performant as the first option.