table常用工具函数 - 表用法

 table_ext.lua

---如果table不为空则新建
function table.getEmptyTable(tb)
    if nil == tb or nil ~= next(tb) then
        return {}
    end
    return tb
end

function table.isEmpty(tb)
    return nil == tb or nil == next(tb)
end

function table.swap(tb, k1, k2)
    local temp = tb[k1]
    tb[k1] = tb[k2]
    tb[k2] = temp
end

function table.mergeTable(tb, mergeTb)
    local count = 0
    for k, v in pairs(mergeTb) do
        tb[k] = v
        count = count + 1
    end
    return tb, count
end

查找

function table.findItem(tb, item)
    for k, v in pairs(tb) do
        if v == item then
            return k, v
        end
    end
    return nil
end

function table.findMatch(tb, matchFunc)
    for k, v in pairs(tb) do
        if matchFunc(k, v) then
            return k, v
        end
    end
    return nil
end

function table.ipairsFindItem(tb, item)
    for i, v in ipairs(tb) do
        if v == item then
            return i, v
        end
    end
    return -1
end

function table.ipairsFindMatch(tb, matchFunc)
    for i, v in ipairs(tb) do
        if match(i, v) then
            return i, v
        end
    end
    return -1
end

 

posted @ 2023-05-17 23:11  yanghui01  阅读(117)  评论(0)    收藏  举报