Search code examples
lua

Why is this string not splitting in lua


So I am working on a project and I need to split a string that would look something like this:

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

This is my code:

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

I need to split the string at "(" so t[1] is only equal to "x" and t[2] is equal to 2 and then t[3] is equal to the "output()"

But when I run my code(note I haven't added the t[3]) t[1] returns: "x "Hello") }" and t[2] returns 2 like it should.

Anyways why isn't the split function working on the first split but it works on the second.

Thanks!


Solution

  • In your loop you set firstSplit true if it hits a ( this happens in 2 places in your example, before x and right before "Hello"

    you can fix this by setting firstSplit true and ignore the leading if ( before you beginning the loop. Then you allow the logic you have to handle the rest.

    I also notice you dont have any logic that references t[3] right now.


    That all said you really should use a pattern to parse something like this.

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

    this pattern is very narrow and expects a specific type of if statement, you can learn more about lua patterns here: Understanding Lua Patterns