Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassigning strings to a set list of values in an array

I have a list in Lua which is fixed format (it's an input from somewhere else).

E.g.

a = {"apple", "apple 1", "pear", "orange", "orange 3", "kiwi", "tomato"}

I also have a look up table where I want to normalise this set and send them to a code format. Note: anything containing apple, such as apple 1, apple 2 etc will be mapped to the same value as apple.

E.g.

"apple" => "RD"
"pear" => "GR"
"orange" => "OG"
"kiwi" => "GR"
"tomato" => "RD"
"banana" => "YL"
etc...

I then want to return a list with all of these substitutions:

fruitBox = {"RD", "GR", "OG"}

I don't mind if fruitBox has repeated values or not, whatever is easiest, but it should only return values if they are represented in both the lookup and the original list. I have been trying to do this but matching the strings, but I always end up getting stuck with how to output the codes. I also tried string.gsub and iterating through a for loop but still got nowhere useful.

like image 228
Gamora Avatar asked Nov 18 '25 14:11

Gamora


1 Answers

You need to store the list of mappings in a (hash) table and iterate over the first list changing the elements using the mapping from the second table. Something like this should work:

local a = {"apple", "pear", "orange", "kiwi", "tomato"}
local map = {
  apple = "RD",
  pear = "GR",
  orange = "OG",
  kiwi = "GR",
  tomato = "RD",
  banana = "YL",
}
for index = 1, #a do
  a[index] = map[a[index]] or "missing mapping"
end

-- print results
for index = 1, #a do print(a[index]) end

This prints RD GR OG GR RD for me.

If you really want to skip the elements not present in the mapping (which I don't recommend, as it will be difficult to find errors in the mapping or the data), then use a separate table and do table.insert instead of a[index]... assignment in the loop.

If the strings have some non-letters (as in the updated question), you may want to remove them using gsub("%A","") or something similar.

like image 105
Paul Kulchenko Avatar answered Nov 21 '25 09:11

Paul Kulchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!