Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function explode(str, delim)
- assert(type(str) == "string", "Bad argument #1 to 'explode', expected string, got " .. type(str) .. ".")
- assert(type(delim) == "string", "Bad argument #2 to 'explode', expected string, got " .. type(delim) .. ".")
- assert(string.len(delim) == 1, "Function 'explode' only supports single-character delimiters.")
- local strings = { }
- local from = 1
- local tpos = 0
- local dfrom, dto = string.find(str, delim, from)
- while dfrom do
- strings[tpos] = string.sub(str, from, dfrom-1)
- tpos = tpos + 1
- from = dto + 1
- dfrom, dto = string.find(str, delim, from)
- end
- table.insert(strings, string.sub(str, from))
- return strings
- end
- --Example usage
- for i,v in pairs(explode("this#is#a#string", "#")) do
- print(v)
- end
- --[[
- -Output:
- this
- is
- a
- string
- ]]
- --OR
- print(explode("this#is#a#string", "#")[1])
- --[[
- -Output:
- is
- ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement