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)

  

posted @ 2022-03-08 17:22  齐齐大佬998  阅读(327)  评论(0编辑  收藏  举报