daily pastebin goal
47%
SHARE
TWEET

Untitled

a guest Jun 19th, 2017 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function explode(str, delim)
  2.     assert(type(str) == "string", "Bad argument #1 to 'explode', expected string, got " .. type(str) .. ".")
  3.     assert(type(delim) == "string", "Bad argument #2 to 'explode', expected string, got " .. type(delim) .. ".")
  4.     assert(string.len(delim) == 1, "Function 'explode' only supports single-character delimiters.")
  5.    
  6.     local strings = { }
  7.     local from = 1
  8.     local tpos = 0
  9.     local dfrom, dto = string.find(str, delim, from)
  10.    
  11.     while dfrom do
  12.         strings[tpos] = string.sub(str, from, dfrom-1)
  13.         tpos = tpos + 1
  14.         from = dto + 1
  15.         dfrom, dto = string.find(str, delim, from)
  16.     end
  17.    
  18.     table.insert(strings, string.sub(str, from))
  19.    
  20.     return strings
  21. end
  22.  
  23. --Example usage
  24.  
  25. for i,v in pairs(explode("this#is#a#string", "#")) do
  26.     print(v)
  27. end
  28.  
  29. --[[
  30.  -Output:
  31.     this
  32.     is
  33.     a
  34.     string
  35. ]]
  36.  
  37. --OR
  38.  
  39. print(explode("this#is#a#string", "#")[1])
  40.  
  41. --[[
  42.   -Output:
  43.     is
  44. ]]
RAW Paste Data
Top