所以我正在创建一个脚本,我得到了一个函数:
loot()
返回:
{"3 gold coins"}
{"3 gold coins"}
{"nothing"}
{"6 gold coins", "a hand axe"}
{"12 gold coins", "a hand axe"}
我希望该功能包含在表格中,表格应为“a”,“an”,“没有数字前的数字”= 1
所以表读取并执行计数示例:
table = {"gold coins"=24,"nothing"=1,"hand axe"=2}
这是我正在寻找的那种表,但我目前没有成功。就像我之前说的那样,我的函数loot()
返回那些消息,这些消息不是唯一的消息,但是我想保存它们的数字或“a”,“an”作为1的数值,所以如果它是当它属于“金币”消息时,“6金币”将这6个分开并在表中增加它。我希望你能理解我在这里的观点。
这样做的目的是显示表值,以便我可以这样做:
table["gold coin"] = 24
或
table = {["item"]="count",}
所以我可以请求密钥。我真的想要一个增加一个键的表,而不是一个普通的表,但我只是想不出怎么做...
提前致谢
如果你能解释我的每一部分,我将非常感激:)
其他一些消息:
{"11 gold coins", "a leather helmet", "meat", "a spear", "a gold coin"}
{"a gold coin"}
btw这个程序,我用来做这个非常有限。我可以使用它,它在lua手册5.1链接下:http://www.lua.org/manual/5.1/manual.html
metatables不是一个选项:/
答案 0 :(得分:2)
您需要的第一件事是从字符串中提取数字和项目名称的函数。下面的内容将读取“矛”或“11矛”之类的内容,并返回1,“长矛”和11,“长矛”。
function parseAmountAndItem(str)
assert(type(str)=="string", "Expected a string. Got a " .. type(str))
-- handle "nothing"
if str == "nothing" then return nil end
local item, amount
-- return 1 when it begins with a/an + space
_,_,item = str:find("^an? (.+)$")
if item then
amount = 1
else -- it should begin with a number + space + singular + s
_,_,amount,item = str:find("^(%d%d?%d?%d?%d?) (.+)s$")
assert(amount and item, "Could not parse the string: " .. str)
amount = tonumber(amount)
end
return amount, item
end
然后你需要累积这些值。这应该有效:
function accumulatedLoot()
local result = {}
local amount, item
for _,row in ipairs(loot())
for _,str in ipairs(row)
local amount, item = parseAmountAndItem(str)
if item then
result[item] = (result[item] or 0) + amount
end
end
end
return result
end
一些警告: