lua-users home
lua-l archive

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


In message <200608192249.31585.stefan.beyer@bluewin.ch> you wrote:

> 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
no - ok
> ..........................
> What is going on? Did I miss something?

The patterns [^,]* and ,? can both match the empty string,
and are doing just that to give you the third match. I suggest
using an extra ',' as a sentinel.

So replace line 3 by

   local s = str..','
   for e in s:gmatch "([^,]*)," do

-- 
Gavin Wraith (gavin@wra1th.plus.com)
Home page: http://www.wra1th.plus.com/