This file is inspired from string exploding :
http://love2d.org/wiki/String_exploding
stringimprove.lua
Code: Select all
local function explode(str, div, plain)
div = div or "[%s\r\n]+"
plain = plain or false
assert(type(str) == "string", "bad argument #1 to 'str' (string expected, got "..type(str)..")")
assert(type(div) == "string", "bad argument #2 to 'div' (string expected, got "..type(div)..")")
local o = {}
while true do
local pos1,pos2 = str:find(div, nil, plain)
if not pos1 then
o[#o+1] = str
break
end
o[#o+1],str = str:sub(1,pos1-1),str:sub(pos2+1)
end
return o
end
local function split(str, div)
div = div or " "
return string.explode(str, div, true)
end
local function join(tbl, sep)
sep = sep or " "
assert(type(tbl) == "table", "bad argument #1 to 'tbl' (table expected, got "..type(tbl)..")")
assert(type(sep) == "string", "bad argument #1 to 'sep' (string expected, got "..type(sep)..")")
return table.concat(tbl, sep)
end
local function apply(s, t)
s = s or string
t = t or table
s.explode = explode
s.split = split
s.join = join
t.join = join
end
local M = {}
M.explode = explode
M.split = split
M.join = join
M.apply = apply
return M
Code: Select all
require("stringimprove").apply()
tbl = string.split("foo bar", " ")
print(tbl[1]) --> foo
-- since we added explode to the string table, we can also do this:
str = "foo bar"
tbl2 = str:split(" ")
print(tbl2[2]) --> bar
-- to restore the original string, we can use Lua's table.concat:
original = string.join(tbl, " ")
print(original) --> foo bar
x="a.b.c.d"
x2=string.split(x, ".")
print(string.join(x2, " "))
EDIT:
minor changes to allow syntax :
Code: Select all
x="a.b.c.d"
x2=x:split(".")
print(x2:join(" "))