# Script: sprite.layers

**URL:** https://community.aseprite.org/t/script-sprite-layers/7051
**Category:** Help
**Created:** [September 27, 2020, 11:51am UTC](https://community.aseprite.org/t/script-sprite-layers/7051 "2020-09-27T11:51:45Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Olga\_Galvanova](https://community.aseprite.org/user_avatar/community.aseprite.org/olga_galvanova/32/3294_2.png) [@Olga\_Galvanova](https://community.aseprite.org/u/Olga_Galvanova)
#### Post date: [September 27, 2020, 11:51am UTC](https://community.aseprite.org/t/script-sprite-layers/7051/1 "2020-09-27T11:51:45Z")

</div>

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?

---

<div class="post-metadata">

### Author: ![dacap](https://community.aseprite.org/user_avatar/community.aseprite.org/dacap/32/10_2.png) [@dacap](https://community.aseprite.org/u/dacap)
#### Post date: [September 27, 2020, 3:29pm UTC](https://community.aseprite.org/t/script-sprite-layers/7051/2 "2020-09-27T15:29:33Z")

</div>

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:

```lua
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

```

---

<div class="post-metadata">

### Author: ![Olga\_Galvanova](https://community.aseprite.org/user_avatar/community.aseprite.org/olga_galvanova/32/3294_2.png) [@Olga\_Galvanova](https://community.aseprite.org/u/Olga_Galvanova)
#### Post date: [September 27, 2020, 3:32pm UTC](https://community.aseprite.org/t/script-sprite-layers/7051/3 "2020-09-27T15:32:03Z")

</div>

i see, thank you very much, david!
