lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I do not understand the behaviour of string.gmatch (using Lua 5.1.1)
I was writing this, to split a csv string:

function split(str)
   local t = {}
   for e in string.gmatch(str,"([^,]*),?") do
      table.insert(t,e)
   end
   return t
end

Here the result:

split("1,Test") -> {'1','Test',''}  -- nok
split(",4") -> {'','4',''}  -- nok
split("2,") -> {'2',''}  -- ok !!

To make the function work as expected, I had to 'artificially' break
at the end of the string:

function split2(str)
   local t = {}
   for e,c in string.gmatch(str,"([^,]*)(,?)") do
      table.insert(t,e)
      if c == "" then break end
   end
   return t
end

which produces what I expect:

split("1,Test") -> {'1','Test'}  -- ok
split(",4") -> {'','4'}  -- ok
split("2,") -> {'2',''}  -- ok

What is going on? Did I miss something?
Any help appreciated, thanks! Stefan