Get next variable by name

Sadly, I had the script done before, but I didn’t publish it, and I forgot the way I did it :pensive:
My target is, that the script gets next variable by it’s name. So basically, theres Part1 and Part2, and I want it to check if Part2 is the next part of Part1, how would I do that? I think I’ve done it in a for i, v loop, but I forgot the main way I found the next part

if you parts are stored in like folder or something do this


local folder = workspace.folder --path to your folder

for index,part in ipairs(folder:GetChildren()) do
  if not folder:FindFirstChild("Part"..(tonumber(string.gsub(part.Name,"%d+") + 1) then continue end

 local part1 = part
 local part2 = folder:FindFirstChild("Part"..(tonumber(string.gsub(part.Name,"%d+") + 1)
end

image
thats all i get

local my_part = folder:FindFirstChild("Part" .. index)

Is this what you need? I do not understand “if Part2 is the next part of Part1”. Could you clarify what you are using this for?

I have this folder, and I want to get next camera by those numbers in the cameras name
image

so something like this?

local currentIndex = 1

local camera = Cameras:FindFirstChild("ShackCamera" .. currentIndex)
if camera then
    -- wohoo
end

local nextCamera = Cameras:FindFirstChild("ShackCamera" .. (currentIndex + 1))
if nextCamera then
    currentIndex += 1
    -- next camera code
end
1 Like

For some reason, it just doesnt work

local function getNextCamera(Shack)
	local currentIndex = 1

	local nextCamera = workspace.Shack.Cameras:FindFirstChild("ShackCamera" .. (currentIndex + 1))
	print('123') -- it prints this
	if nextCamera then
		currentIndex += 1
		print(currentIndex) -- it doesnt print this
		return nextCamera -- it doesnt return anything
	end
end

Oops, sorry, it works! I just forgot the rename the parts after some changes

1 Like

it should at least print. There is still an error that currentIndex is a local variable in the function scope, it will always reset to 1 when the function is called, thus always returning camera2.

If you can, simply declare it outside the function

local currentIndex = 1
local function getNextCamera(Shack)
    -- etc ...
1 Like