Search code examples
arraysstringlualua-tablelua-patterns

Creating arrays in Lua from list returned by gmatch


I am programming in Lua and so far I have this.

S=tostring(M[i].AllSegmentsList)      --it returns "MSH, PID"
for i in string.gmatch(S, ",") do      --I have  ", " as delimiter 
  t= {}        --Now, I want the values returned by delimiter to be added into an array.
end

How can I do that.


Solution

  • Declare the table before, and add the elements in the loop like this:

    local t = {}
    for i in S:gmatch("([^,%s]+)") do  
        t[#t + 1] = i
    end 
    

    The pattern [^,%s]+ matches one or more non-comma, non-space characters.