写一些可复用的Lua函数

判断元素是否在table中

local item_if_in_table = function(item, tablename)
    for i=1, #tablename do
       if tablename[i] == item then
           return true
       end
    end
end

截取table中的前多少个元素,返回一个截取后的table

local table_top_slice = function(table_name, top_number)
    local n = 0
    local result_table = {}
    for k, v in ipairs(table_name) do
        if n == top_number then
            break
        end
        table.insert(result_table, v)
        n = n + 1
    end

    return result_table
end

读取操作系统中的文件,返回一个table

local _M = {}

local function load_file()

    local iplib_file = ngx.config.prefix() .. "/conf/lua/lib/ipipnet.txt"
    local iplib_func = io.lines(iplib_file)
    local iplib_list = {}

    while true do
        local line = iplib_func()
        if line then
            table.insert(iplib_list, line)
        else
            break
        end
    end

    return iplib_list
end

-- model level variable, share data for all requests of the worker.
-- so, do not put this in the function level(request level).
local iplib_list = load_file()

_M.get_iplib_table = function()
    return iplib_list
end


return _M

持续更新…