其他分享
首页 > 其他分享> > Lua表元素去重小测试

Lua表元素去重小测试

作者:互联网

local tab1 = {1,2,3,5,9,7,8}
local tab2 = {3,4,5,7,6,2}

local tab3,tab4  = {},{}

for _,v in pairs(tab2) do
	tab1[#tab1 + 1] = v
end

for _,v in  pairs(tab1) do
	tab3[v] = true
end

for k in pairs(tab3) do
	tab4[#tab4 +1]= k
end

table.foreachi(tab4, print)

-- 数组表去除重复元素
function ArrayTableUnique(t)
  local check = {}
  local n = {}

  for key, value in ipairs(t) do
	if not check[value] then
	  check[value] = value
	  n[#n +1] = value
	end
  end

  return n
end

-- 哈希表去除重复元素
function TableUnique(t)
  local check = {}
  local n = {}

  for key, value in pairs(t) do
    print ("key="..key, "value="..value)
	if not check[value] then
	  check[value] = value
	  n[key] = value
	end
  end

  return n
end


print "---------------------------"
local t = ArrayTableUnique(tab1)
table.foreachi(t, print)

  

标签:do,end,重小,value,tab1,Lua,测试,local,check
来源: https://www.cnblogs.com/welcome-to-fang-qi-blog/p/15981496.html