Search code examples
stringselectlualua-table

LUA select specific string in table


I have a problem to recover values from a LUA table.

Table (string):

table = {
key = "/get value0\n/get [opt1][opt2] value1\n/get [opt1][opt2][opt3][opt4] value2\n/get value3\n/get [opt1] value4",
},

is it possible to select "/get" and "value0" for the first line. and "/get" and "value1 or 2 / 3 / 4" on all other lines ?

I think I have an idea for it to work, but easier to say than to do

  • 1) Counts total number of "\n" and add one.
  • 2) Select first "/" and first space.
  • 3) Select last "]" if present or last space before value.
  • 4) repeat the operation for each line.

result:

/get value0 
/get value1 
/get value2 
/get value3 
/get value4

Solution

  • Try this code:

    s=[[
    /get value0
    /get [opt1][opt2] value1
    /get [opt1][opt2][opt3][opt4] value2
    /get value3
    /get [opt1] value4
    ]]
    
    for l in s:gmatch("(/.-)\n") do
        print((l:gsub("%b[]%s*","")))
    end
    

    It first spits the string into lines and then removes all strings in brackets optionally followed by spaces.

    A simpler match is l:gsub(" .* "," "), which will remove everything from the first space to the last.

    If you want to split the resulting string, use this code:

    for l in s:gmatch("(/.-)\n") do
        local var1, var2 = l:gsub(" .* "," "):match("(.*) (.*)$")
        print(var1, var2 )
    end