我一直在开发一个saycommand系统的这一部分,该部分应该将字符串的各个部分分离并放入一个表格中,然后将该表格发送到一个函数中,在字符串的开头进行查询。例如:
我希望将这个字符串转换成一个表格:
!save 1
、!teleport 0 1
或!tell 5 "a private message"
。
我希望将这个字符串转换成一个表格:
[[1 2 word 2 9 'more words' 1 "and more" "1 2 34"]]
字符串中每个没有被引号包含的部分都将成为一个键,而被引号包含的部分将会被分组成为一个键。
1 = 1
2 = 2
3 = word
4 = 2
5 = 9
6 = more words
7 = 1
8 = and more
9 = 1 2 34
我曾尝试利用Lua模式来实现这个,但我卡在了如何捕获字符串中既带引号又不带引号的部分。我尝试了很多方法,但都没有帮助。
目前我的模式看起来像这样:
a, d = '1 2 word 2 9 "more words" 1 "and more" "1 2 34"" ', {}
-- previous attempts
--[[
This one captures quotes
a:gsub('(["\'])(.-)%1', function(a, b) table.insert(d, b) end)
This one captures some values and butchered quotes,
which might have to do with spaces in the string
a:gsub('(["%s])(.-)%1', function(a, b) table.insert(d, b) end)
This one captures every value, but doesn't take care of quotes
a:gsub('(%w+)', function(a) table.insert(d, a) end)
This one tries making %s inside of quotes into underscores to
ignore them there, but it doesn't work
a = a:gsub('([%w"\']+)', '%1_')
a:gsub('(["\'_])(.-)%1', function(a, b) table.insert(d, b) end)
a:gsub('([%w_]+)', function(a) table.insert(d, a) end)
This one was a wild attempt at cracking it, but no success
a:gsub('["\']([^"\']-)["\'%s]', function(a) table.insert(d, a) end)
--]]
-- This one adds spaces, which would later be trimmed off, to test
-- whether it helped with the butchered strings, but it doesn't
a = a:gsub('(%w)(%s)(%w)', '%1%2%2%3')
a:gsub('(["\'%s])(.-)%1', function(a, b) table.insert(d, b) end)
for k, v in pairs(d) do
print(k..' = '..v)
end
对于简单的命令,这种操作是不需要的。但是像 !tell 1 2 3 4 5 "a private message sent to five people"
这样更加复杂的命令则需要它,首先是检查它是否发送给了多个人,然后才能找到消息。
将来,我还想添加像 !give 1 2 3 "component:material_iron:weapontype" "food:calories"
这样的命令,它可以为三个不同的人添加两个物品,这样的系统将会极大地受益。
如果Lua模式无法实现这一点,我将尝试使用for循环等方法,但我真的觉得自己错过了一些显而易见的东西。难道我想太多了吗?