我正在尝试简化脚本,我的尝试失败了。我正在创建一个函数,它将传递给定的参数并将它们转换为索引表,但我希望能够传递引用和非引用的相似内容,并让函数识别引用的参数被认为是一个值,同时也尊重非引用的参数。
例如:
makelist dog“棕色老鼠”猫虎“多彩鹦鹉”
应该返回一个索引表,如下所示:
list_table = {"dog", "brown mouse", "cat", "tiger", "colorful parrot"}
我为引用而编写的代码,但它正在弄乱未引用的内容,并且最重要的是,第二次添加引用的参数。这就是我所拥有的:
function makelist(str)
require 'tprint'
local list_table = {}
for word in string.gmatch(str, '%b""') do
table.insert(list_table, word)
end
for word in string.gmatch(str, '[^%p](%a+)[^%p]') do
table.insert(list_table, word)
end
tprint(list_table)
end
我不明白为什么忽略引号被忽略,而且也是在切掉第一个字母。也就是说,这是我从tprint收到的输出(打印表格的函数,与代码无关):
makelist('dog "brown mouse" cat tiger "colorful parrot"')
1=""brown mouse""
2=""colorful parrot""
3="og"
4="rown"
5="mouse"
6="cat"
7="tiger"
8="olorful"
9="parrot"
如您所见,'d','b'和'c'缺失。我需要做些什么修复才能获得以下输出?
1="brown mouse"
2="colorful parrot"
3="dog"
4="cat"
5="tiger"
或者更好的是,如果可能的话,让他们保持相同的命令作为参数。
答案 0 :(得分:2)
local function makelist(str)
local t = {}
for quoted, non_quoted in ('""'..str):gmatch'(%b"")([^"]*)' do
table.insert(t, quoted ~= '""' and quoted:sub(2,-2) or nil)
for word in non_quoted:gmatch'%S+' do
table.insert(t, word)
end
end
return t
end
答案 1 :(得分:2)
简单地在空格上拆分并连接引号内的元素可能更容易。这样的东西可能会起作用(我添加了几个测试用例):
function makelist(str)
local params, quoted = {}, false
for sep, word in str:gmatch("(%s*)(%S+)") do
local word, oquote = word:gsub('^"', "") -- check opening quote
local word, cquote = word:gsub('"$', "") -- check closing quote
-- flip open/close quotes when inside quoted string
if quoted then -- if already quoted, then concatenate
params[#params] = params[#params]..sep..word
else -- otherwise, add a new element to the list
params[#params+1] = word
end
if quoted and word == "" then oquote, cquote = 0, oquote end
quoted = (quoted or (oquote > 0)) and not (cquote > 0)
end
return params
end
local list = makelist([[
dog "brown mouse" cat tiger " colorful parrot " "quoted"
in"quoted "terminated by space " " space started" next "unbalanced
]])
for k, v in ipairs(list) do print(k, v) end
这将为我打印以下列表:
1 dog
2 brown mouse
3 cat
4 tiger
5 colorful parrot
6 quoted
7 in"quoted
8 terminated by space
9 space started
10 next
11 unbalanced
答案 2 :(得分:1)
首先感谢你的问题,让我学习Lua的基础知识!
其次,所以我认为你的解决方案有点误导。看看我刚刚说过的问题,为什么不用引号(")拆分一次,而不是选择你想要按空格分割的位置。
这就是我提出的:
function makelist(str)
local list_table = {}
i=0
in_quotes = 1
if str:sub(0,1) == '"' then
in_quotes = 0
end
for section in string.gmatch(str, '[^"]+') do
i = i + 1
if (i % 2) == in_quotes then
for word in string.gmatch(section, '[^ ]+') do
table.insert(list_table, word)
end
else
table.insert(list_table, section)
end
end
for key,value in pairs(list_table) do print(key,value) end
end
结果:
1 dog
2 brown mouse
3 cat
4 tiger
5 colorful parrot