lua-users home
lua-l archive

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


In message <200510080450.j984ovd21421@carbon.laserlab.com> you wrote:

> How does one do the equivalent of
> the following Perl code:
> 
> ($name,$birthyear,$sex) = split();

I use:

-- use as: for i,field in split(text,pat) do ... end
split = function (t,p)
        local pat,n,count,L = "(.-)"..p, 1,0,#t
        local f = function (s,v)
                  local i,j,x = s:find(pat,n)
                  if i then
                    count = count + 1
                    n = j + 1
                    return count,x
                  elseif n < L then
                    count = count + 1
                    x = s:sub(n,-1)
                    n = L + 1
                    return count,x
                  end -- if
                  end -- function
        return f,t,n
        end -- function

so you could do

 pieces = {}
 for i,item in split(text,pattern) do
  pieces[i] = item
 end -- for

The advantage of defining an iterator rather than
a list is that for large numbers of items you have
the option of processing them with constant storage
rather than storage that depends linearly on the
number of items.

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