Script: sprite.layers

i’m trying to make a simple script which would delete all hidden layers, so far i have this:

local sprite = app.activeSprite 

for i, layer in ipairs(sprite.layers) do 
	if (not layer.isVisible) then 
		print(i)
		app.activeLayer = sprite.layers[i] 
		app.command.RemoveLayer() 
	end
end 

the issue is following:

  • when there’s only one hidden layer, everything is fine - that layer gets deleted
  • however with more than one hidden layer i get an error: [string “internal”]:1: Using a nil ‘Layer’ object after the layer above the hidden layer gets deleted. and then the script stops because of error.

interestingly print(i) returns correct number - if the hidden layers are for example nr. 1 and 5, those are values i get on screen, but before the script stops it deletes layers nr. 1 and 6 (not 5).
i guess it is because the sprite.layers value and/or index of layers change instantly? if so, how to deal with it?

Hi @Olga_Galvanova, this is a common problem when we have to remove elements from a collection that is being iterated. In this case the problem is that we cannot go through the sprite.layers collection and modify it at the same time.

My recommendation would be to create a table of layers first, and then iterate that table:

local sprite = app.activeSprite
local layers = {}
for i, layer in ipairs(sprite.layers) do
  table.insert(layers, layer)
end
for i, layer in ipairs(layers) do
  if not layer.isVisible then
    app.activeLayer = layer
    app.command.RemoveLayer()
  end
end
1 Like

i see, thank you very much, david!

1 Like