Iterate over paths while using GSLayer.connectPathsWithNode_andNode_()

I’m scratching my head. I know this is quite a basic, classic problem, but I can’t quite figure it out. I want to connect these paths with each other using GSLayer.connectPathsWithNode_andNode_(). No, I don’t just want to use “close open paths”.

How do I correctly do this? Iterating over the paths doesn’t work, since I change the paths list by connecting the paths. Any ideas? Thanks!

You put the iteration in a function. When it connects something, it breaks the iteration and returns True. When it iterates without connecting anything, you return (at the end) False.

The code that calls the function is in a while loop. The while loop tests a variable that is (inside the while loop) set to the result of the function.

Found a way:

for index in range(len(Layer.paths) - 1):
	Layer.connectPathsWithNode_andNode_(list(Layer.paths[0].nodes)[-1], Layer.paths[1].nodes[0])
Layer.connectPathsWithNode_andNode_(list(list(Layer.paths)[-1].nodes)[-1], Layer.paths[0].nodes[0])

I can always start at the first path of the layer and connect it with the second one, and that simply as often as there are paths in the layer, minus one. Then just close the path at the end.

Looks like you can also collect the nodes and reconnect them (in case the paths are in random order).

node_pairs = []
for path in Layer.paths:
	for path2 in Layer.paths:
		if path.nodes[0].position == list(path2.nodes)[-1].position:
			node_pairs.append([path.nodes[0], list(path2.nodes)[-1]])
			break

for node1, node2 in node_pairs:
	Layer.connectPathsWithNode_andNode_(node1, node2)

I can’t use that approach, since the nodes in my actual project are not at the same locations. That’s why I need to work with indexes. My code above is what works for my use case.