Getting table entry index

I can not get the index of the input table. I need to remove an item from a table.

I use table.insertto add records to the table.

Another question: why doesn't Lua have an “overload” for the table.remove function, so can an element be deleted with an associative index?

+3
source share
2 answers

t[k]=nilremoves the tkey entry from the record k.

In the second question, the answer is that tables can have separate meta tags.

+1
source

. , () , .

k, t[k] = nil , . .

table.insert table.remove , 1, . , .

, , - . , , , , /, , .

. :

-- 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
+7

Source: https://habr.com/ru/post/1729106/


All Articles