Shift a table by some number

So im trying to shift a table by some amount (like shifting 1, 2, 3, 4 by 1 and you get 4, 1, 2, 3 and i created 2 function for it

function IndexCycle(Index, Table)
	if Index < 1 then
		return #Table-Index
	elseif Index > #Table then
		return Index - #Table
	else
		return Index
	end
end
function ShiftTable(Table, Shift)
	local NewTable = {}
	for Index, _ in pairs(Table) do
		table.insert(NewTable, Table[IndexCycle(Index+Shift, Table)])
	end

	return NewTable
end

theres a problem tho, if i shift by more than the number of objects in the table then it would delete objects(if i do shift 1, 2, 3, 4 by 5 with the function i get 2, 3, 4)

i think the problem is the IndexCycle function but i cant figure out how to fix, i tried using modulus but 0 % 4 = 0 and theres no index 0 and -x % y = y-(x % y) except when x is divisible by y

Fixed it using for loop, IndexCycle remain the same but heres the new ShiftTable function

function ShiftTable(Table, Shift)
	local ReturnTable = Table
	local InternalTable = {}
	local Change
	
	if Shift < 0 then
		Change = -1
	elseif Shift > 0 then
		Change = 1
	else
		return Table
	end
	
	for ChangeIndex = Change, Shift, Change do
		for Index, _ in pairs(ReturnTable) do
			table.insert(InternalTable, ReturnTable[IndexCycle(Index+Change, ReturnTable)])
		end
		
		ReturnTable = InternalTable
		InternalTable = {}
	end

	return ReturnTable
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.