Table.remove not removing

Hey everybody!
Why are there still 2 tables in “mytable”? Actually it should remove all.

local mytable = {
    {"String", 1},
    {"String", 2},
    {"String", 3},
    {"String", 4},
    {"String", 5},
}

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

print(unpack(mytable))

When you remove a table’s index, the table if shifted to fill the gap. The ipairs loop will still loop 1 - #myTable, but the indexes i will no longer be accurate.

If you want to clear the entire table, it would be much easier to overwrite it. myTable = {}

1 Like

Thanks for your answer, unfortunately I don’t want to just clear it. I need to do some actions before I use table.remove. How could I achieve that the right table gets removed?

If your end-goal is to clear all the values, it’s best to do what @MayorGnarwhal said, unless you have other references to that table that need to remain intact. You can just scan through all the items first before clearing it:

for i,v in ipairs(mytable) do
-- Stuff
end
mytable = {}

Hm okay that will work probably. Thanks for your replies.

local mytable = {
    {"String", 1},
    {"String", 2},
    {"String", 3},
    {"String", 4},
    {"String", 5},
}

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

Sorry to bump an old topic - but for anyone wanting to do it the iterative way, setting each element to nil seems to work better.

2 Likes

Yeah, I came to that solution in the end as well.

1 Like