How to "flip" an array

Say I have

local a = {1,2,3,4}

how could I get it to be

{4,3,2,1}

None of these worked, I ended up just sampling it in reverse

1 Like

You could just index starting from the last element of a table using -1.

1 Like

Use table.sort and return true if a is bigger than b:

table.sort(
    t,
    function(a, b)
        return a > b
    end
)

This will sort the table from biggest to smallest.


If you wanted to actually “flip” a table, you can iterate over the length of the table and use the last index:

local newTable = {}

for index = 1, #table do
    newTable[#table - index] = table[index] -- Flips the table. Setting each value to its opposite index
end

I found this function:

function ReverseTable(t)
    local reversedTable = {}
    local itemCount = #t
    for k, v in ipairs(t) do
        reversedTable[itemCount + 1 - k] = v
    end
    return reversedTable
end

Which converts {1,2,3,4} to {4,3,2,1} and {9,3,6,4} to {4,6,3,9}.

1 Like

i’m sorry maybe my example was a bit off. I have a 2d array that represents an image and need to flip it vertically and i dont think you can compare arrays

1 Like

Loop through the table and swap the position’s item with a corresponding position’s item, e.g.: if we are at position 2 of the table, we get the corresponding position by subtracting 2 from the end of the table (basically the total number of items in the table).

We should also stop looping the table when we get to the middle position, else we just swap everything back to their original positions.

local a = {1, 2, 3, 4}

for i = 1, math.floor(#a/2) do
     a[i], a[#a - (i - 1)] = a[#a - (i - 1)], a[i]
end

#a - (i-1) is the corresponding position, instead of just #a - i, due to Roblox’s arrays starting from position 1.

1 Like

This can essentially be achieved in a few lines of code:

local array = {1, 5, 4, 7, 2}
local reversed = {}

for i = #array, 1, -1 do
	local val = array[#array]
	table.insert(reversed, val)
end
1 Like

underated solution, this can be optimized even further too, by approximately 35%

	local l = #a
	for i = 1, math.floor(l / 2) do
		local b = l - (i - 1) 
		a[i], a[b] = a[b], a[i]
	end