Diff

util/array.lua @ 11787:3ae6fa901a8b

util.array: Add :slice() method + tests Behaviour follows the same logic as string.sub (so yes, 1-indexed).
author Matthew Wild <mwild1@gmail.com>
date Sun, 12 Sep 2021 10:50:20 +0100
parent 10895:5777968301e8
child 12403:42b2713ab818
child 13138:0b0cefce6e42
line wrap: on
line diff
--- a/util/array.lua	Sun Sep 12 10:31:02 2021 +0100
+++ b/util/array.lua	Sun Sep 12 10:50:20 2021 +0100
@@ -114,6 +114,40 @@
 	return outa;
 end
 
+function array_base.slice(outa, ina, i, j)
+	if j == nil then
+		j = -1;
+	end
+	if j < 0 then
+		j = #ina + (j+1);
+	end
+	if i < 0 then
+		i = #ina + (i+1);
+	end
+	if i < 1 then
+		i = 1;
+	end
+	if j > #ina then
+		j = #ina;
+	end
+	if i > j then
+		for idx = 1, #outa do
+			outa[idx] = nil;
+		end
+		return outa;
+	end
+
+	for idx = 1, 1+j-i do
+		outa[idx] = ina[i+(idx-1)];
+	end
+	if ina == outa then
+		for idx = 2+j-i, #outa do
+			outa[idx] = nil;
+		end
+	end
+	return outa;
+end
+
 function array_base.sort(outa, ina, ...)
 	if ina ~= outa then
 		outa:append(ina);