Question

I can't get table entry index. I need it to remove an item from table.

I use table.insert to add entries to table.

Another question: why Lua doesn't have "overload" to function table.remove so one can remove item by associative index?

Was it helpful?

Solution

t[k]=nil removes from t the entry with key k.

For the second question, the answer is that tables can have individual metatables.

OTHER TIPS

Tables implement an unordered one to many relation between keys and values. In other words, any particular key (index) can only appear once in a table, but a value can appear multiple times.

If you know the key k, then t[k] = nil will remove both the key and the associated value from the table. However, this operation has no effect on any other keys or values in the table.

The table.insert and table.remove functions operate over the set of sequential integer keys beginning at 1, that are used by convention to implement arrays or lists. For that purpose, they manipulate other values in the list so as to keep the list from developing holes.

One way to find a key at which some value is found is to simply search the table. If this will be done more than once, then it is probably a good idea to build a second table that inverts the key/value pairs so that lookup by value is as fast as lookup by index.

A suitable implementation will depend on your assumptions and needs. Some samples are:

-- return the first integer index holding the value 
function AnIndexOf(t,val)
    for k,v in ipairs(t) do 
        if v == val then return k end
    end
end

-- return any key holding the value 
function AKeyOf(t,val)
    for k,v in pairs(t) do 
        if v == val then return k end
    end
end

-- return all keys holding the value
function AllKeysOf(t,val)
    local s={}
    for k,v in pairs(t) do 
        if v == val then s[#s+1] = k end
    end
    return s
end

-- invert a table so that each value is the key holding one key to that value 
-- in the original table.
function Invert(t)
    local i={}
    for k,v in pairs(t) do 
        i[v] = k
    end
    return i
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top