Lua 数字模式匹配未捕获

Lua digit pattern matching not capturing

我正在尝试匹配以下字符串中的 Sword2

You receive loot [Sword]x2.

这是我到目前为止所做的。 Sword 匹配良好并保存在 item 变量中。但是,无论输入字符串如何,数量总是 returns 'No qty'。

local item, qty = msg:match('%[(.+)%]x?(%d?)') or 'No item', 'No qty'

问题不在于您的模式,而是多重赋值与 or 一起工作的方式。您实际拥有的是(注意粗体括号):

local item, qty =(msg:match('%[(.+)%]x?(%d?)') or 'No item'), 'No qty'

因此,qty 始终 分配 'No qty'。我不认为这个问题可以在一个语句中解决。你必须做这样的事情:

local item, qty = msg:match('%[(.+)%]x?(%d?)')
item = item or 'No item'
qty = qty or 'No qty'

local item, qty = msg:match('%[(.+)%]x?(%d?)')
item, qty = item or 'No item', qty or 'No qty'

关于模式,您可能希望使用 %[(.+)%]x?(%d*),即 * 而不是 ?,数量为 10 或更多。