为什么这个字符串在lua中不能分割

所以我正在做一个项目,我需要分割一个类似于这样的字符串:

if (x == 2){ output("Hello") }

这是我的代码:

local function splitIfStatement(str)
    local t = {}
    t[1] = ""
    t[2] = ""
    t[3] = ""
    local firstSplit = false
    local secondSplit = false
    local thirdSplit = false
    str:gsub(".", function(c)
        if c == "(" then
            firstSplit = true
        end
        if firstSplit == true then
            if c == "=" then
                firstSplit = false
                secondSplit = true
            else
                if c == "(" then
                else
                    t[1] = t[1] .. c
                end
            end
        end
        if secondSplit == true then
            if c == ")" then
                secondSplit = false
                thirdSplit = true
            else
                if c == "=" then
                else
                    t[2] = t[2] .. c
                end
            end
        end
    end)
    return t
end

我需要在 "(" 上分割字符串,所以t \ [1 ]只等于 "x",t \ [2 ]等于2,然后t \ [3 ]等于 "output()"。但是当我运行我的代码时(请注意我还没有添加t \ [3 ]),t \ [1 ]返回:"x"Hello") }",t \ [2 ]返回2,就像它应该的那样。无论如何,为什么第一个分割函数不起作用,但是第二个函数可以。谢谢!

原文链接 https://stackoverflow.com/questions/68924107

点赞
stackoverflow用户107090
stackoverflow用户107090

如果输入的形式是

if (AAA == BBB){ CCC("Hello") }

则可以在问题字段周围保留可能的空格,然后这段代码就可以工作:

S=[[if (x == 2){ output("Hello") } ]]
a,b,c = S:match('%(%s*(.-)%s.-%s+(.-)%)%s*{%s*(.-)%(')
print(a,b,c)
2021-08-25 14:52:33
stackoverflow用户7396148
stackoverflow用户7396148

在你的循环中,如果它遇到了 (,你会将 firstSplit 设置为 true,这在你的示例中发生了两次,分别是在 x 之前和在 "Hello" 前面。

你可以通过在开始循环之前将 firstSplit 设置为 true 并忽略前导的 if ( 来修复这个问题。然后你可以让你已经拥有的逻辑来处理剩下的部分。

我还注意到你现在没有任何引用 t[3] 的逻辑。


话虽如此,你真的应该使用一个模式来解析这样的东西。

local function splitIfStatement(str)
    t = {str:match("if%s*%((%w+)%s*[=<>]+%s*(%d+)%)%s*{(.+)}")}
    return t
end

这个模式非常狭窄,期望的是一个特定类型的 if 语句,你可以在这里了解更多关于 Lua 模式的知识:理解 Lua 模式

2021-08-25 14:59:37