Lua: remove duplicate elements

I have a table in lua

  test = {1,2,4,2,3,4,2,3,4, "A", "B", "A"}

I want to delete all duplicate items in a table. The exit should be

  test = {1,2,4,3, "A", "B"}

EDIT:

My attempt:

  > items = {1,2,4,2,3,4,2,3,4, "A", "B", "A"}
 > flags = {}
 > for i = 1, table.getn (items) do
 if not flags [items [i]] then
       io.write ('' .. items [i])
       flags [items [i]] = true
    end
 >> end
  1 2 4 3 A B>

Now it works fine. Thanks for the answers and comments.

+6
source share
3 answers

Similar to @Dimitry example, but only one loop

local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"} local hash = {} local res = {} for _,v in ipairs(test) do if (not hash[v]) then res[#res+1] = v -- you could print here instead of saving to result table if you wanted hash[v] = true end end 
+13
source
 local test = {1,2,4,2,3,4,2,3,4,"A", "B", "A"} -- make unique keys local hash = {} for _,v in ipairs(test) do hash[v] = true end -- transform keys back into values local res = {} for k,_ in pairs(hash) do res[#res+1] = k end -- 1 2 3 4 AB for _,v in ipairs(res) do print(v) end test = res 

... a simple, direct solution only from the head, but I think the hint is given in the PiL book

What did you try to solve the problem?

+4
source
  > items = {1,2,4,2,3,4,2,3,4, "A", "B", "A"}
 > flags = {}
 > for i = 1, table.getn (items) do
 if not flags [items [i]] then
       io.write ('' .. items [i])
       flags [items [i]] = true
    end
 >> end
  1 2 4 3 A B>
0
source

Source: https://habr.com/ru/post/958369/


All Articles