Comparison

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
comparison
equal deleted inserted replaced
11786:39164ea2ab9e 11787:3ae6fa901a8b
109 for i = write, start_length do 109 for i = write, start_length do
110 outa[i] = nil; 110 outa[i] = nil;
111 end 111 end
112 end 112 end
113 113
114 return outa;
115 end
116
117 function array_base.slice(outa, ina, i, j)
118 if j == nil then
119 j = -1;
120 end
121 if j < 0 then
122 j = #ina + (j+1);
123 end
124 if i < 0 then
125 i = #ina + (i+1);
126 end
127 if i < 1 then
128 i = 1;
129 end
130 if j > #ina then
131 j = #ina;
132 end
133 if i > j then
134 for idx = 1, #outa do
135 outa[idx] = nil;
136 end
137 return outa;
138 end
139
140 for idx = 1, 1+j-i do
141 outa[idx] = ina[i+(idx-1)];
142 end
143 if ina == outa then
144 for idx = 2+j-i, #outa do
145 outa[idx] = nil;
146 end
147 end
114 return outa; 148 return outa;
115 end 149 end
116 150
117 function array_base.sort(outa, ina, ...) 151 function array_base.sort(outa, ina, ...)
118 if ina ~= outa then 152 if ina ~= outa then