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

3 Likes

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}.

4 Likes

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

for some reason when i use this and the amount of things in the table is even then it doesnt work idk why lol

strange, altho that is like something i wrote 2 years ago, heres an improved version of that which ive tested to work perfectly.

also old solution was arbitury as hell seriously im sorry for that xd

local function flipList(list: {}): nil
	local listSize: number = #list
	local listSize_half: number = listSize / 2
	local listSize_plus1: number = listSize + 1--why did i do this in the loop before?
	
	for index: number = 1, listSize_half do--again not sure why i used math.floor here in the old example lol, completely pointless
		local index_inverse: number = listSize_plus1 - index
		
		list[index], list[index_inverse] = list[index_inverse], list[index]
	end
	
	return list
end
1 Like
local tbl = {1, 2, 3}
setmetatable(tbl, {
	__unm = function(t)
		local content = {}
		for i = #t, 1, -1 do
			table.insert(content, t[i])
		end
		return content
	end,
})

print(-tbl)
3 Likes