Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

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 operation it would be {a, b, c, d, e}

Alternatively, and probably preferably, is there a way to add an element to a table, but only if it is not already contained within the table.

<\noobquestion>

like image 489
Colton Phillips Avatar asked Jul 08 '11 00:07

Colton Phillips


3 Answers

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:

values[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 values like this:

for k,_ in pairs(values) do
  -- k contains the internal tables
end
like image 54
kikito Avatar answered Nov 19 '22 11:11

kikito


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
like image 39
Jane T Avatar answered Nov 19 '22 11:11

Jane T


It sounds like you're trying to implement a Set, a collection of unique elements. This article might help you: http://www.lua.org/pil/13.1.html

like image 8
2rs2ts Avatar answered Nov 19 '22 10:11

2rs2ts