Gamora
Gamora

Reputation: 347

How to remove repeated string values from a list

This is a continuation of a previous question.

I have a fixed list in Lua which I am reassigning values for

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}
colours = {}
for index = 1, #a do
  table.insert(colours,map[a[index]or "OT")
end

Now I would either like to edit the existing script, or add some new script, to remove any repeated values.

My end result should be a table (colours) with no repeated values or empty strings, but I can't seem to think of a neat way to do this!

If it's not possible (or really messy) my second option would be to count the number unique values in the table.

Upvotes: 3

Views: 156

Answers (2)

Piglet
Piglet

Reputation: 28950

If you don't want to run over the entire table every time you add an element you can simply create a second table where you remember which colours have been listed yet. Simply use the colour as key.

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}

local listedColours = {}
local colours = {}
for _,colour in pairs(a) do
  colour = map[colour] or "OT"
  if not listedColours[colour] then
    table.insert(colours, colour)
    listedColors[colour] = true
  end      
end

Upvotes: 4

Andrew Kashpur
Andrew Kashpur

Reputation: 746

Solution i suggest: add to table function contains

table.contains = function(t, value)
    for index = 1, #t do
        if t[index] == value then
            return index    
        end
    end
end

so problem with having only unique colours can be solved like:

for index = 1, #a do
    local colour = map[a[index]] or "OT"
    if not table.contains(colours, colour) then
        table.insert(colours, colour)
    end
end

I consider it pretty neat

Upvotes: 3

Related Questions