Array reverse library function

As a developer it’s weirdly annoying to reverse an array. Usually a much more time- and space-consuming task than it should be. Seems like this should just be a library function.

Easy use case: I have some data that I need to display either ascending or descending. Like sorting inventory items by recency.

I want a table.reverse(a) that just reverses the array in place.

3 Likes
for i = 1, math.floor(#array/2), 1 do
    array[i], array[#array-i+1] = array[#array-i+1], array[i]
end

Not that time and space consuming, but can be usefull function.

3 Likes

this could benefit greatly using a similar optimisation as table.move but with a reverse index rather than a positive index.

2 Likes

This would be the most optimal way to do it manually.

local function Reverse(Array: {any})
	local Length = #Array
	
	for Index = 1, Length / 2 do
		local Offset = Length - Index + 1
		Array[Index], Array[Offset] = Array[Offset], Array[Index]
	end
end

I think I rarely ever want to actually mutate an array’s order, though. In you’re use case, why can’t you just iterate the array backwards?

for Index = #Array, 1, -1 do
	local Value = Array[Index]
end

If anything, we should be asking for some ‘reverse ipairs’ iterator, which would solve both these cases.

4 Likes