Version 3.69 of MUSHclient adds a new Lua script function: utils.split. This was suggested by Ked.
This is intended to do the reverse of table.concat. That is, it takes a
string and generates a table of entries, delimited by single-character
delimiters (such as comma or newline).
Example:
test = "the,quick,brown,dog,jumped"
t = utils.split (test, ",")
tprint (t)
print (table.concat (t, ","))
Output:
1="the"
2="quick"
3="brown"
4="dog"
5="jumped"
the,quick,brown,dog,jumped
You pass utils.split 2 or 3 arguments:
- The string to be split
- The single-character delimiter
- (optional) the maximum number of splits to do
If the 3rd argument is not supplied, or is zero, then the entire string
is split. Otherwise, it will be split the number of times you specify.
eg.
t = utils.split (test, ",", 2)
tprint (t)
Output:
1="the"
2="quick"
3="brown,dog,jumped"
In this case the remaining text is placed in the 3rd table item.
static int l_split (lua_State *L) {
const char *s = luaL_checkstring(L, 1);
const char *sep = luaL_checkstring(L, 2);
const int count = (int) luaL_optnumber (L, 3, 0);
char *e;
int i = 1;
if (strlen (sep) != 1)
luaL_error (L, "Separator must be a single character");
if (count < 0)
luaL_error (L, "Count must be positive or zero");
lua_newtable(L); /* result */
/* repeat for each separator */
while ((e = strchr(s, *sep)) != NULL &&
(count == 0 || i <= count))
{
lua_pushlstring(L, s, e-s); /* push substring */
lua_rawseti(L, -2, i++);
s = e + 1; /* skip separator */
}
/* push last substring */
lua_pushstring(L, s);
lua_rawseti(L, -2, i);
return 1; /* return the table */
}
function split (s, delim)
assert (type (delim) == "string" and string.len (delim) > 0,
"bad delimiter")
local start = 1
local t = {} -- results table
-- find each instance of a string followed by the delimiter
while true do
local pos = string.find (s, delim, start, true) -- plain find
if not pos then
break
end
table.insert (t, string.sub (s, start, pos - 1))
start = pos + string.len (delim)
end -- while
-- insert final one (after last delimiter)
table.insert (t, string.sub (s, start))
return t
end -- function split