Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can i make a table to shift it's elemets circularly?

I'm trying to shifts the elements of a table so that every elements goes up and that the first element becomes the last one.

local listTable = function(mesa, up)
	local exchange = nil
	if up then
		exchange = mesa[0]
		for i = 1, #mesa do
			mesa[i - 1] = mesa[i]
		end
		mesa[#mesa] = exchange
	else
		exchange = mesa[#mesa]
		for i = #mesa, 1 do
			mesa[i] = mesa[i - 1]
		end
		mesa[0] = exchange
	end
end

2 answers

✓ Accepted answer

table.remove and table.insert shift elements around when you remove/insert at the ends (or in the middle). You can use this to get this shift without writing any loop at all.

It can be concisely written in one statement, too:

-- 1, 2, 3, 4 --> 2, 3, 4, 1

-- Specifically:
-- 1, 2, 3, 4 --remove--> 2, 3, 4 --insert--> 2, 3, 4, 1

local oldFirst = table.remove(list, 1)
table.insert(list, oldFirst)

-- In one statement:

table.insert(list, table.remove(list, 1))


-- 1, 2, 3, 4 --> 4, 1, 2, 3

-- Specifically:
-- 1, 2, 3, 4 --remove--> 1, 2, 3 --insert--> 4, 1, 2, 3

local oldLast = table.remove(list)
table.insert(list, 1, oldLast)

-- In one statement:

table.insert(list, 1, table.remove(list))

The easiest way to do this is to set the value in the new array to the value in the old array at the same index plus the amount you want to shift it by. In your case you want to set the value to the value stored at the previous index of the original array, which can be done by accessing it as index - 1.

However, we have to take in account the bounds of the array. Because we want it to wrap around, we can set the first value of the new array to the last value in the original array.

local function shiftTable(array)
	local newArray = {array[#array]}
	for i = 2, #array do
		newArray[i] = array[i - 1]
	end
	return newArray
end

This discussion is preserved as it was. New answers, comments, and votes are closed.