6

I've been trying to find a way to remove a string from a table kind of like this:

myTable = {'string1', 'string2'}
table.remove(myTable, 'string1')

but I haven't been able to find anyway to do it. Can someone help?

ryanpattison
  • 6,151
  • 1
  • 21
  • 28
Lysus
  • 61
  • 1
  • 2

2 Answers2

4

As hjpotter92 said, table.remove expects the position you want removed and not the value so you will have to search. The function below searches for the position of value and uses table.remove to ensure that the table will remain a valid sequence.

function removeFirst(tbl, val)
  for i, v in ipairs(tbl) do
    if v == val then
      return table.remove(tbl, i)
    end
  end
end

removeFirst(myTable, 'string1')
ryanpattison
  • 6,151
  • 1
  • 21
  • 28
  • 1
    http://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating#comment16660887_12397742 – hjpotter92 Sep 27 '15 at 10:16
  • 1
    This is `removeFirst` and for that there is no better way, this is linear time. lhf's answer is for a linear time `removeAll`, which could be updated to use `table.move` – ryanpattison Sep 27 '15 at 10:24
2

table.remove accepts the position of an element as its second argument. If you're sure that string1 appears at the first index/position; you can use:

table.remove(myTable, 1)

alternatively, you have to use a loop:

for k, v in pairs(myTable) do -- ipairs can also be used instead of pairs
    if v == 'string1' then
        myTable[k] = nil
        break
    end
end
hjpotter92
  • 78,589
  • 36
  • 144
  • 183