【发布时间】:2015-02-15 09:45:14
【问题描述】:
我一直在研究 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 循环等,但我真的觉得我错过了一些明显的东西。我是不是想多了?
【问题讨论】:
标签: string lua lua-patterns