Lua: Smartest way to add to table only if not already in table, or remove duplicates

前端 未结 3 1016
清歌不尽
清歌不尽 2021-01-11 17:51

I have a table of strings. I\'d like an easy way to remove all of the duplicates of the table.

So if the table is {a, b, c, c, d, e, e} , after this ope

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 18:47

    The simplest way is using the tables as keys, not as values, in your "container table".

    Let's call the container table values. You must currently be doing something similar to this for adding elements to it:

    table.insert(values, value)
    

    And you parse values like this:

    for i,v in ipairs(values) do
      -- v contains the internal values
    end
    

    In order to have the tables just once, you can insert them this other way:

    t[value] = 1
    

    This will ensure that the inserted values (strings, tables, numbers, whatever) are included just once, because they will be 'overwritten'.

    Then you can parse t like this:

    for k,_ in pairs(values) do
      -- k contains the internal tables
    end
    

提交回复
热议问题