btpoole
11 years agoChannel Surfer
Array Range
Is there any way to extract a set number of values stored in an array. For example in the the array myarray I only want the first 10 entries in the array.
Thanks
Thanks
first_ten = []
for i = 0 to 9
first_ten.Push(my_array[i])
end for
function arraySlice(arr, start=invalid, finish=invalid, step_=1):
if step_ = 0 then print "ValueError: slice step cannot be zero" : STOP
if start = invalid then if step_ > 0 then start = 0 else start = arr.count() - 1
if finish = invalid then if step_ > 0 then finish = arr.count() - 1 else finish = 0
if start < 0 then start = arr.count() + start 'negative counts backwards from the end
if finish < 0 then finish = arr.count() + finish
res = [ ]
for i = start to finish step step_:
res.push(arr[i])
end for
return res
end function
BrightScript Debugger> a = [00,11,22,33,44]
BrightScript Debugger> ? arraySlice(a, 2, 3)
22
33
BrightScript Debugger> ? arraySlice(a, 3)
33
44
BrightScript Debugger> ? arraySlice(a, invalid, -3)
0
11
22
BrightScript Debugger> ? arraySlice(a, invalid, invalid, -2)
44
22
0
"btpoole" wrote:
I can live with the small code to do it, but was looking for a one liner.
mySlice = arraySlice(myArray, 0, 9) 'returns the 10 first elementsIs that not good enough? It even does party tricks, like say when called with no extra params, `arraySlice(arr)` makes a copy of the array.