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

前端 未结 3 993
清歌不尽
清歌不尽 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:52

    What I normally do for this is index the table on the string so for example

    tbl[mystring1] = 1
    tbl[mystring2] = 1
    

    etc.

    When you add a string you simply use the lines above and duplicates will be taken care of. You can then use a for ... pairs do loop to read the data.

    If you want to count the number of occurrences

    use something like

    if tbl[mystring1] == nil then
      tbl[mystring1] = 1
    else
      tbl[mystring1] = tbl[mystring1] + 1
    end
    

    As the end of the addition cycle if you need to turn the table around you can simply use something like

    newtbl = {}
    for s,c in pairs(tbl) do
      table.insert(newtbl,s)
    end
    

提交回复
热议问题