Getting table entry index
snippet in lua

Getting table entry index

user8121

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