lua 判断table数据元素的数量

记录:lua 判断table数据元素的数量:#table
示例:

local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
    ngx.say("failed to instantiate mysql: ", err)
    return
end
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect{
     
    host = "",
    port = 3306,
    database = "",
    user = "",
    password = "",
    max_packet_size = 1024 * 1024 }

if not ok then
    ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
    return
end
ngx.say("connected to mysql.")
-- 检查是否存在要生成的cors配置 config
local select_sql = "select * from config where name='"..name.."' order by createtime asc"
local corsconfig,err,errno,sqlstate = db:query(select_sql)
if not corsconfig then	
	ngx.say("select rows error:",err,",errno:",errno,",sqlstate:",sqlstate)
	break
end
-- 判断corsconfig(table数据)元素的数量:#corsconfig
if #corsconfig ~= 0 then
    -- 循环此cdn服务下的所有CORS配置
	for j,corsrow in ipairs(corsconfig) do
	    -- 调用函数:生成单个cors配置文件
	    createCorsConf(corsrow,name)
	end
end

但这种方法要慎用,使用过程中,遇到过这种bug:

    local t = {
     "a", "a", "b", "b","c"} -- 重复的 a 会被过滤掉
    LuaPrintTable(t,'table')
    ngx.print(#t)   -- 打印结果:5
    
    -- 过滤掉重复的元素
    local n = uniqueTable(t)
    LuaPrintTable(n,'table')
    ngx.print(#n)   -- 打印结果:1
    do return end

打印图示:

lua 判断table数据元素的数量_第1张图片

你可能感兴趣的:(lua,lua,table数量)