【问题标题】:Lua string.gsub inside string.gmatch?string.gmatch 里面的 Lua string.gsub?
【发布时间】:2015-03-13 10:42:23
【问题描述】:

我创建了这个简单的示例脚本来输出食物列表。如果食物是水果,那么也会显示水果的颜色。我遇到的问题是处理“草莓”的不规则复数形式。

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

现在程序输出:

potatoes
apples = green
strawberries
carrots
crab-apples

我想要的是:

potatoes
apples = green
strawberries = red
carrots
crab-apples

我不明白为什么这不能像我想要的那样工作!

【问题讨论】:

    标签: lua gsub lua-patterns


    【解决方案1】:

    首先,你在这里拼错了草莓:

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

    您还可以将 lua 表作为集合使用,这意味着无需使用嵌套循环搜索重复项。它可以简化为:

    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
    

    【讨论】:

    • 很高兴,我犯了那个愚蠢的错字,因为我现在知道集合了!非常感谢!
    【解决方案2】:

    stawberry 应该是strawberry。循环将strawberries 更改为strawberry,然后尝试将strawberry^stawberry 匹配,但拼写错误导致它不匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 2015-05-18
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 2015-07-20
      相关资源
      最近更新 更多