常用操作函数 | lua helper function

lua helper function

ps: 使用 _G.function_name 定义可以实现全局函数

字符串分隔成数组

-- splite str to arr by symbol 
function explode(str, symbol)
    local rt= {}
    string.gsub(str, '[^'..symbol..']+', function(w) table.insert(rt, w) end )
    return rt
end

将数组使用给定符号拼接成字符串

-- make up a string from array
function implode(arr, symbol)
    local implode_str = ''
    symbol = symbol or ','
    for key, value in pairs(arr) do
        implode_str = implode_str .. value .. symbol
    end
    return string.sub(implode_str, 1, #implode_str - 1)
end

将数组 table 逆向

function table_reverse(tbl)
    for i=1, math.floor(#tbl / 2) do
        tbl[i], tbl[#tbl - i + 1] = tbl[#tbl - i + 1], tbl[i]
    end
    return tbl
end

删除 table 中的一个给定的元素

-- remove item in table
function G.table_remove(tab, rm)
    local result = tab
    for k, v in pairs(rm) do
        for a_k, a_v in pairs(result) do
            -- array
            if type(a_k) == 'number' then
                -- object
                if type(a_v) == 'table' then
                    result[a_k][v] = nil
                elseif v == a_v then
                    table.remove(result, a_k)
                end
            else
            -- hash array
                if v == a_k then
                    result[a_k] = nil
                end
            end
        end
    end
    return result
end

对数组型 table 去重

-- unique a array
function G.unique(arr)
    local hash = {}
    local res = {}
    for _,v in ipairs(arr) do
        if not hash[v] then
            hash[v] = true
            table.insert(res, v)
        end
    end
    return res
end

对 hash table 按 key 排序

-- sort a hashTable by key
-- use example: for k,v in pairsByKeys(hashTable)
function sortByKey(f)
    local a = {}
    for n in pairs(self) do
        table.insert(a, n)
    end
    table.sort(a, f)
    local i = 0 -- iterator variable
    local iter = function()
        -- iterator function
        i = i + 1
        if a[i] == nil then
            return nil
        else
            return a[i], self[a[i]]
        end
    end
    return iter
end
点赞