lua-users home
lua-l archive

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


I’ve used this split (string to table) method I found here: http://stackoverflow.com/questions/1426954/split-string-in-lua.

 

I’ve got it working, but I don’t understand it.

 

function string:split(delimiter)

      local result = { }  

      local from  = 1  

      local delim_from, delim_to = string.find( self, delimiter, from  )  

      while delim_from do    

            table.insert( result, string.sub( self, from , delim_from-1 ) )    

            from  = delim_to + 1    

            delim_from, delim_to = string.find( self, delimiter, from  )  

      end  

      table.insert( result, string.sub( self, from  ) )  

      return result

end

 

This is how I’m calling it:

 

local myDateString = "2011-06-21"

local myDateTbl = myDateString.split(myDateString,"-")

dump_table(myDateTbl)

 

 

1=2011

2=06

3=21

 

Two things I don’t understand:

1] When I call it, I reference it twice: myDateString.split(myDateString,"-")Why? Or should I just do this:  string.split(myDateString,"-") Which works, so I guess the answer is yes.

 

2] The function takes one parameter (delimiter), but I must pass it two (myDateString, "-"). If I only pass it the delimiter string like it seems to want, it breaks. Why does it take two when it looks like it takes one?

 

Are these both occurring because I’m not really writing a function, I’m really modifying the string prototype?

 

 

Dave Collins

Front-End Engineer

Mercatus Technologies Inc.
60 Adelaide Street East, Suite 700
Toronto ON M5C 3E4
T  416 603 3406 x 298
F  416 603 1790

 

dave.collins@mercatustechnologies.com

www.mercatustechnologies.com