Search code examples
lualua-table

Remove specific entry from Lua table


I am inserting into a table like this

Admin = {}

table.insert(Admins, {id = playerId, Count = 0})

And that works fine.

How do I remove that specific admin from that table now?

The following does not work, and Im sure its because ID is stored in an array that's inside of the table, but how would I access that then?

table.remove(Admins, playerId)

Basically, I want to remove from the table Admins, where the ID == playerId that I input.


Solution

  • There are two approaches to remove an entry from the table, both are acceptable ways:

    1. myTable[index] = nil
    Removes an entry from given index, but adds a hole in the table by maintaining the indices

    local Admins = {}
    table.insert(Admins, {id = 10, Count = 0})
    table.insert(Admins, {id = 20, Count = 1})
    table.insert(Admins, {id = 30, Count = 2})
    table.insert(Admins, {id = 40, Count = 3})
    
    
    local function removebyKey(tab, val)
        for i, v in ipairs (tab) do 
            if (v.id == val) then
              tab[i] = nil
            end
        end
    end
    -- Before
    -- [1] = {['Count'] = 0, ['id'] = 10},
    -- [2] = {['Count'] = 1, ['id'] = 20},
    -- [3] = {['Count'] = 2, ['id'] = 30},
    -- [4] = {['Count'] = 3, ['id'] = 40}}
    removebyKey(Admins, 20)
    -- After
    -- [1] = {['Count'] = 0, ['id'] = 10},
    -- [3] = {['Count'] = 2, ['id'] = 30},
    -- [4] = {['Count'] = 3, ['id'] = 40}
    

    2. table.remove(myTable, index)
    Removes the entry from given index and renumbering the indices

    local function getIndex(tab, val)
        local index = nil
        for i, v in ipairs (tab) do 
            if (v.id == val) then
              index = i 
            end
        end
        return index
    end
    local idx = getIndex(Admins, 20) -- id = 20 found at idx = 2
    if idx == nil then 
        print("Key does not exist")
    else
        table.remove(Admins, idx) -- remove Table[2] and shift remaining entries
    end
    -- Before is same as above
    -- After entry is removed. Table indices are changed
    -- [1] = {['id'] = 10, ['Count'] = 0},
    -- [2] = {['id'] = 30, ['Count'] = 2},
    -- [3] = {['id'] = 40, ['Count'] = 3}