
|
  
Split function for lua Summary A function to split a string into smaller parts, using an arbitrary separator. It uses pattern matching by default, unless true is given for the plain parameter.
| Example split=require('split') split("one two three four five", "%s+")
| returns
| {"one", "two", "three", "four", "five"} |
Download here Code
local split=
function(text, sep, plain)
local res={}
local searchPos=1
while true do
local matchStart, matchEnd=string.find(text, sep, searchPos, plain)
if matchStart and matchEnd >= matchStart then
table.insert(res, string.sub(text, searchPos, matchStart-1))
searchPos=matchEnd+1
else
table.insert(res, string.sub(text, searchPos))
break
end
end
return res
end
local verif=
function(teststr, pat, plain, check)
local res=split(teststr, pat, plain)
res=table.concat(res, "*")
assert(res==check, "split self test assertion failed")
end
verif("one|-two|-three|-four|-five", "%|%-", false, "one*two*three*four*five")
verif("|-one|-two|-three|-four|-|-five|-", "%|%-", false, "*one*two*three*four**five*")
verif("one1two22three333four4444five", "%d+", false, "one*two*three*four*five")
verif("one1two22three333four4444five", "%d+", true, "one1two22three333four4444five")
verif("", "%S+", false, "")
verif("abcdefg", "", false, "abcdefg")
verif("one two three four five", "%s+", false, "one*two*three*four*five")
return split
  
© Markus Nentwig 2007-2008
The content of this page is provided without any warranty and may not be reproduced without permission.
Comments? Questions?
Please send me a mail!
mnentwig@elisanet.fi
|