Lua - 查找表中是否存在某一key值或value值

代码如下:

-- 查看某值是否为表tbl中的key值
function table.kIn(tbl, key)
    if tbl == nil then
        return false
    end
    for k, v in pairs(tbl) do
        if k == key then
            return true
        end
    end
    return false
end

-- 查看某值是否为表tbl中的value值
function table.vIn(tbl, value)
    if tbl == nil then
        return false
    end

    for k, v in pairs(tbl) do
        if v == value then
            return true
        end
    end
    return false
end

table_item={
[1]=25,
[15000]=15000,
[150008]={150008},
[9]='码农码农!!',
[150010]=3002,
[2]={{25,},},
}

local id = 150008
if table.kIn(table_item, id) then
    print("表中存在数值为" .. id .. "的key值")
else
    print("表中不存在数值为" .. id .. "的key值")
end
if table.vIn(table_item, id) then
    print("表中存在数值为" .. id .. "的value值")
else
    print("表中不存在数值为" .. id .. "的value值")
end

输出如下:

表中存在数值为150008的key值
表中不存在数值为150008的value值

 

你可能感兴趣的:(lua)