[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Unexpected behaviour of string.gmatch
- From: Gavin Wraith <gavin@...>
- Date: Sat, 19 Aug 2006 22:09:58 +0100
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/