Search code examples
luagsublua-patterns

Lua string.gsub inside string.gmatch?


I've created this simple example script to output a list of foods. If the food is a fruit then the color of the fruit will be displayed as well. The issue I'm having is in dealing with the irregular pluralization of 'strawberries.'

fruits = {apple = "green", orange = "orange", stawberry = "red"}
foods = {"potatoes", "apples", "strawberries", "carrots", "crab-apples"}

for _, food in ipairs(foods) do
    for fruit, fruit_colour in pairs(fruits) do
        duplicate = false
        if (string.match(food, "^"..fruit) or string.match((string.gsub(food, "ies", "y")), "^"..fruit)) and not(duplicate) then -- this is where the troubles is!
            print(food.." = "..fruit_colour)
            duplicate = true
            break
        end
    end
    if not(duplicate) then
        print(food)
    end
end

Right now the program outputs:

potatoes
apples = green
strawberries
carrots
crab-apples

What I want is:

potatoes
apples = green
strawberries = red
carrots
crab-apples

I can't figure out why this doesn't work like I want it to!


Solution

  • Well for one thing, you miss-spelled strawberry here:

    fruits = {apple = "green", orange = "orange", stawberry = "red"}
    

    You can also work with lua tables as sets, which means that nested loop searching for duplicates is unnecessary. It can be simplified to something like:

    fruits = {apple = "green", orange = "orange", strawberry = "red"}
    foods = {"potatoes", "apples", "strawberries", "carrots", "crab-apples"}
    
    function singular(word)
        return word:gsub("(%a+)ies$", "%1y"):gsub("(%a+)s$", "%1")
    end
    
    for _, food in ipairs(foods) do
        local single_fruit = singular(food)
        if fruits[single_fruit] then
            print(food .. " = " .. fruits[single_fruit])
        else
            print(food)
        end
    end