View Single Post
  #4  
Unread 03-18-2011, 11:00 AM
Garan's Avatar
Garan Garan is offline
The Undying
Interface Author - Click to view interfaces
 
Join Date: Oct 2010
Posts: 340
you can also easily implement string.split using string.gmatch:
Code:
string.split=function(str,separator)
local tmpArray={};
local tmpElem;
 if string.find("^$()%.[]*+-?",separator,1,true)~=nil then separator="%"..separator end
 for tmpElem in string.gmatch(str,"[^"..separator.."]+") do
  table.insert(tmpArray,tmpElem);
 end
 return tmpArray;
end
then use the same as your original split function:
Code:
args = string.split(args, " ");
This version also allows using control characters, including "%" as separators.

EDIT: After playing with it a bit, I realized that the simple solution I originally posted doesn't account for "empty" values between separator characters and neither the original nor the simple version accounted for empty values at the end of the string. So, a more complete (but slightly uglier) version is:
Code:
string.split=function(str,separator)
 local tmpArray={};
 local tmpElem;
 str=tostring(str);
 if string.find("^$()%.[]*+-?",separator,1,true)~=nil then separator="%"..separator end
 for tmpElem in string.gmatch(str,"[^"..separator.."]*") do
  table.insert(tmpArray,tmpElem);
 end
 local tmpIndex=1;
 while tmpIndex<=#tmpArray do
  if tmpIndex==#tmpArray and tmpArray[tmpIndex]=="" then
   table.remove(tmpArray,tmpIndex);
  else
   if tmpArray[tmpIndex]=="" and tmpArray[tmpIndex+1]~="" then
    table.remove(tmpArray,tmpIndex);
   else
    tmpIndex=tmpIndex+1;
   end
  end
 end
 return tmpArray;
end

Last edited by Garan : 03-23-2011 at 01:00 PM. Reason: original solution was incomplete
Reply With Quote