gpt4 book ai didi

Lua string.gsub 里面的 string.gmatch?

转载 作者:行者123 更新时间:2023-12-04 18:41:43 24 4
gpt4 key购买 nike

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

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

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

最佳答案

一方面,你在这里拼错了 strawberry:

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

关于Lua string.gsub 里面的 string.gmatch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com