StringLib: Support seperators in string.rep

This commit is contained in:
gamax92
2019-08-11 12:07:47 +02:00
committed by asie
parent 626664a0fe
commit 244eb4b1a1

View File

@@ -669,20 +669,33 @@ public class StringLib extends TwoArgFunction {
} }
/** /**
* string.rep (s, n) * string.rep (s, n [, sep])
* *
* Returns a string that is the concatenation of n copies of the string s. * Returns a string that is the concatenation of n copies of the string s
* separated by the string sep. The default value for sep is the empty
* string (that is, no separator).
*/ */
static final class rep extends VarArgFunction { static final class rep extends VarArgFunction {
public Varargs invoke(Varargs args) { public Varargs invoke(Varargs args) {
LuaString s = args.checkstring( 1 ); LuaString s = args.checkstring(1);
int n = args.checkint( 2 ); int n = args.checkint(2);
final byte[] bytes = new byte[ s.length() * n ]; LuaString sep = args.optstring(3, EMPTYSTRING);
if (n <= 0)
return EMPTYSTRING;
int len = s.length(); int len = s.length();
for ( int offset = 0; offset < bytes.length; offset += len ) { int lsep = sep.length();
s.copyInto( 0, bytes, offset, len ); final byte[] bytes = new byte[len * n + lsep * (n - 1)];
int offset = 0;
while (n-- > 1) {
s.copyInto(0, bytes, offset, len);
offset += len;
if (lsep > 0) {
sep.copyInto(0, bytes, offset, lsep);
offset += lsep;
} }
return LuaString.valueUsing( bytes ); }
s.copyInto(0, bytes, offset, len);
return LuaString.valueUsing(bytes);
} }
} }