Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua string.gsub在string.gmatch中?_Lua_Gsub_Lua Patterns - Fatal编程技术网

Lua string.gsub在string.gmatch中?

Lua string.gsub在string.gmatch中?,lua,gsub,lua-patterns,Lua,Gsub,Lua Patterns,我创建了这个简单的示例脚本来输出食物列表。如果食物是水果,那么水果的颜色也会显示出来。我面临的问题是如何处理“草莓”的不规则多元化 fruits = {apple = "green", orange = "orange", stawberry = "red"} foods = {"potatoes", "apples", "strawberries", "carrots", "crab-apples"} for _, food in ipairs(foods) do for fruit

我创建了这个简单的示例脚本来输出食物列表。如果食物是水果,那么水果的颜色也会显示出来。我面临的问题是如何处理“草莓”的不规则多元化

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

我不明白为什么这不能像我希望的那样工作

stawberry
应该是
草莓
。循环将
草莓
更改为
草莓
,然后尝试将
草莓
^stawberry
匹配,但键入错误导致其不匹配。

首先,您在此处遗漏了草莓的拼写:

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

很高兴,我犯了那个愚蠢的错误,因为我现在知道了集合!非常感谢你!