4

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
systemdebt
  • 4,589
  • 10
  • 55
  • 116

1 Answers1

5

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • @lhf Fixed now. I was over-thinking. – Yu Hao Feb 06 '14 at 11:24
  • `%w` assumes the items are words formed with letter and digits, which is fine for the example given, but may not be general enough. – lhf Feb 06 '14 at 11:26
  • @lhf I changed it to `[^,%s]+`, hopefully that satisfies the OP's needs. – Yu Hao Feb 06 '14 at 11:33
  • 1
    I would not recommend the `t[#t + 1]` approach. It's better to store the current index in a local variable. With #t Lua has to compute the length of the table at each iteration. – W.B. Feb 06 '14 at 12:21
  • @W.B. If the table is large, I agree with you. I'm using `#` operator because it's more clear and in most cases, the table is small, so the performance is not an issue. – Yu Hao Feb 06 '14 at 12:28
  • Thank you so much , it totally worked. But, can you please please please explain how is "([^,%s]+)" part working? I really need to now this. Thank you – systemdebt Feb 06 '14 at 14:19
  • I know I'm kinda late, but why not use table.insert(t, i)? Does it introduce significant overhead? – xeruf Jul 22 '17 at 10:41
  • @Xerus Both are OK to use. – Yu Hao Jul 23 '17 at 09:22
  • This answer here confirms what @W.B. said, that the length operator `#` isn't free, it does some calculations each time it's called. This answer here points to the relevant Lua interpreter source code: https://stackoverflow.com/a/18208085/4206247 (and if you use LuaJIT, the relevant code is this: https://github.com/LuaJIT/LuaJIT/blob/v2.1/src/lj_tab.c#L640-L686) – R. Navega Apr 27 '22 at 11:23