diff --git a/bytearr.c b/bytearr.c index 2b5768e..78181e4 100644 --- a/bytearr.c +++ b/bytearr.c @@ -825,15 +825,22 @@ static int lbytearr_slice( lua_State *L ) if( end <= 0 ){ end += getLength(p); } - if( start > end || getLength(p) <= start ){ - error_handle(L, ERR_OUTOFRANGE); - lua_error(L); - return 0; - } handle_scope_except(); - - Buf *r = cut(p, start, end-start); + + Buf *r; + if( start > end || getLength(p) <= start ){ // empty array + r = createBuf( BYTEARRAY_RESERVE_SIZE, getNativeEndian() ); + } + else{ + if( start < 0 ){ // set start to 0 ) + start = 0; + } + if( getLength(p) <= end ){ + end = getLength(p); + } + r = cut(p, start, end-start); + } lua_pushlightuserdata(L, r); return 1; } diff --git a/test.lua b/test.lua index 47a4793..1735a06 100644 --- a/test.lua +++ b/test.lua @@ -294,6 +294,16 @@ local function test_slice() for i=1, #e do assert( e[i] == buf[i+#buffer_data-7] ) end + local f = buf:slice( -1000, -1 ) + assert( #f == #buffer_data - 1 ) + for i=1, #f do + assert( f[i] == buf[i] ) + end + local g = buf:slice( -1000, 1000 ) + assert( #g == #buffer_data ) + for i=1, #g do + assert( g[i] == buf[i] ) + end end test_readonly()