LuaString p = args.checkstring( 2 );
LuaValue repl = args.arg( 3 );
int max_s = args.optint( 4, srclen + 1 );
final boolean anchor = p.length() > 0 && p.charAt( 0 ) == '^';
Buffer lbuf = new Buffer( srclen );
MatchState ms = new MatchState( args, src, p );
int soffset = 0;
int n = 0;
while ( n < max_s ) {
ms.reset();
int res = ms.match( soffset, anchor ? 1 : 0 );
if ( res != -1 ) {
n++;
ms.add_value( lbuf, soffset, res, repl );
}
if ( res != -1 && res > soffset )
soffset = res;
else if ( soffset < srclen )
lbuf.append( (byte) src.luaByte( soffset++ ) );
else
break;
if ( anchor )
break;
}
lbuf.append( src.substring( soffset, srclen ) );
return varargsOf(lbuf.tostring(), valueOf(n));
}