Reversing for a,b loop without using #

hello!
i made this code:

		for a,b in ipairs(Folder:GetChildren()) do
				local anglePart = b
				if anglePart then
					local Tween = game.TweenService:Create(script.Parent,TweenInfo.new(1,Enum.EasingStyle.Linear),{CFrame = anglePart.CFrame * CFrame.new(0,0,0)})
					Tween:Play()
					Tween.Completed:Wait()
					-- set camera to this anglePart's CFrame or something
				else
				end

		end

now its sends the part along the checkpoints, starting at the checkpoint called “1”
and ends at the last one. how would i makke it so it does this starting from the last one and stopping at the first one the most simple way?

1 Like

This is simplest solution for reversing a, b loop without using #, I made 2 functions for sorting the table by either ascending or descending order, which can be used when calling for function. Keep in mind that this requires parts to be named by numbers, so it sorts them by number in their name, or could be modified to have some number attribute in it and sort it by that.

function AscendingOrder(tableSent)
	table.sort(tableSent, function(i, j) return tonumber(i.Name) < tonumber(j.Name) end);
	
	return tableSent;
end;

function DescendingOrder(tableSent)
	table.sort(tableSent, function(i, j) return tonumber(i.Name) > tonumber(j.Name) end);

	return tableSent;
end;

for int, anglePart in DescendingOrder(Folder:GetChildren()) do
	if anglePart then
		local Tween = game.TweenService:Create(script.Parent,TweenInfo.new(1,Enum.EasingStyle.Linear),{CFrame = anglePart.CFrame * CFrame.new(0,0,0)});
		Tween:Play();
		Tween.Completed:Wait();
		-- set camera to this anglePart's CFrame or something
	end;
end;

You’d be better off using a standard for loops, which does require the # operator.

local array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

for i = #array, 1, -1 do
	local v = array[i]
	print()
end

If you wrote a custom iter function you’d have to use the # operator to get the array length as well.

The solution above is not optimial because it will also flip the table directly (along with being slow because of the memory overhead of creating new table.sort callbacks), so to use it you’d have to create a clone of the table, which would get messy.

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