Remove value from table without key

I can’t figure this out.

So I want to remove a value from a table without knowing the key of the value, which in Lua doesn’t seem very easy to do.

I researched it online first, however nothing seemed to have worked.

I have a table that holds multiple strings, and this table is retrieved from a datastore.

How can I find a value in this table and remove it?

If you want to remove only a single element, something like this should do the trick:

local function RemoveVal(tbl, val) 
    for i,v in pairs(tbl) do
        if v == val then
            table.remove(tbl,i)
            break
        end
    end
end
2 Likes

As no knowledge of the index/key is known the only way (including other programming languages) is to loop through the data and compare each item.

Just note that the code by @Amiaa16 will remove the element and shift the other elements down ie 1,2,3 remove 2 would result in 1,3. In Lua it is also valid to set the index/key to nil though this can complicate things for arrays using #. ie print(#{1,nil,2,3,nil}) will print 1.

If you don’t have the key of the value you want to remove, something like what @Amiaa16 posted is about the only thing you can do. There’s a couple things I would change about his approach that both have to do with the use of table.remove. First, you generally don’t want to use table.remove for reasons that @kingdom5 detailed in his response. Second, if your table is very large (I’m talking hundreds or thousands of values), your code will take a lot longer to run. I usually use a fast remove method such as this which only takes O(1) time to run:
(Credit to @Kampfkarren)

-- Only works on tables with numerical indices and where order is ambiguous --
local function fastRemove(table, index)
    table[index] = table[#table]
    table[#table] = nil
end

local t = {"a", "b", "c", "d", "e"}
print(unpack(t)) -- "a b c d e"
fastRemove(t, 2)
print(unpack(t)) -- "a e c d"

I would recommend using this method once you find the index of the value you want to remove. Hope this helps!

1 Like

I had a feeling that this would print something else, and I was right
I ran your code and the output I got was a e c d rather than a c d e