Splits a string based on a single character separator and returns an array.
The function is added to the string library and may be called using either the string.split(strText,”+”) or the strText:split(“+”) format as shown in the examples.
Requires: None
Code
-
-- Split a String -- parameter sep Separator, if not supplied uses a comma -- returns a table containing the fields. function string.split(strTxt,strSep) local tblFields = {} local strPattern = string.format("([^%s]+)", strSep or ",") strTxt = tostring(strTxt or "") strTxt:gsub(strPattern, function(strField) tblFields[#tblFields+1] = strField end) return tblFields end -- function string.split
Usage
-
local strString = "Alpha,Gamma,Epsilon" local tblFields = string.split(strString) -- Split strString using default comma print( tblFields[1], tblFields[2], tblFields[3] ) -->> Alpha Gamma Epsilon local strString = "Alpha+Gamma+Epsilon" local tblFields = strString:split("+") -- Split strString using + sign print( tblFields[1], tblFields[2], tblFields[3] ) -->> Alpha Gamma Epsilon