对于新手来说,在lua中在table中如何去除重复的项是个小纠结的问题,捯饬了好久终于找到方法了,问题现状和解决思路如下:
存在重复项的数组table={
"one
","two","three","test","test","test","test","test","test","test","test","test","test","test0","test1","test2","sohu","iqyi","baidu","one","two","three","four"}
解决思路:
(1)、将上述table的value作为key,true为值,构成新的table。在lua中key不允许有重复,因此形成的新数组,就能够实现去重复元素了。
local aa={}
for key,val in pairs(zz) do
aa[val]=true
end
local fan=cjson.encode(aa)
ngx.say(fan)
结果:形成一个新的key,value的table:(已经实现了去重)
{
"one":true,"two":true,"three":true,"iqyi":true,"test":true,"sohu":true,"test1":true,"baidu":true,"test2":true,"test0":true}
(2)、将上述形成table的key作为最终结果,组成table输出:
local bb={}
for key,val in pairs(aa) do
table.insert(bb,key) # 将key插入到新的table,构成最终的结果
end
table.sort(bb)
local fan=cjson.encode(bb)
ngx.say(fan)
得到最终去重后的结果:
{"baidu","four","iqyi","one","sohu","test","test0","test1","test2","three","two"}
达到最终的目的,收工!!!
阅读(21988) | 评论(0) | 转发(0) |