Incorrect fetching of objects in a for-loop

The problem is that in the 2nd cycle only 2 layers are obtained, instead of 20 that are in the folder. I checked the whole script, the problem is in the 2nd cycle.

P.S. Layers are BasePart with attachments, all on the server side.

function layer.LayersInit(folderLayers:Folder,indexLayer:number)
	local layers=folderLayers:GetChildren()
	local layersTable={}
	
	for index,_layer in ipairs(layers) do
		_layer.Name="Layer"..tostring(index)
		local allAttachmentsObject=_layer:GetDescendants()
		
		if not layersTable[index] then
			layersTable[index]={}
		end
		
		layersTable[index][indexLayer]={
			layer=_layer,
			name=_layer.Name,
			attachments=(#allAttachmentsObject>0 and allAttachmentsObject) or nil
		}
	end
	
        --This loop outputs the correct number of layers.
	--for index, layerDataIndex in pairs(layersTable) do
	--	print("Layer index:", index)
	--	for _indexLayer, layerData in pairs(layerDataIndex) do
	--		print(" - Layer name:", layerData.name, "Has attachments:", layerData.attachments ~= nil)
	--	end
	--end
	
	for index,layerDataIndex in pairs(layersTable) do
		for indexLayer,layerData in pairs(layerDataIndex) do
			if layerData.attachments then
				print("Layer has attachments:",layerData.name)
				layer.LayerPreload(layerData.layer,layerDataIndex)
			else
				print("Layer has no attachments:",layerData.name)
				layer.LayerPreload(layerData.layer)
			end
		end
	end
end

is this code run locally (on the client?) or on the server?

I wrote above. This module is initialized only on the server. There are 20 layers in the folder, but for some reason there are only 2 in the cycle.

I found out what the problem was. For some reason, because I called the module in a loop, the loop was processed only 2 times, which is why only 2 layers were initialized.

The solution to the problem is very simple, after the loop processes all the layers, you need to add them all to the table and send them to another module(in my case, this is how it is).

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