Trying to export a sprite but hide the first layer

Ive gota layer that i use as a grid for drawing my tiles. I have to scroll up and hide it each time I export my sprite sheet.

Im trying to write a script to hide the top layer, export, then unhide it. Im getting the error attempt to preform arithmetic on nil value numLayers

-- Get the current sprite
local sprite = app.activeSpriteRoot()

-- Get the number of layers
local numLayers = sprite.layers.count

-- Get the visibility state of the top two layers
local topTwoLayersVisible = {}
topTwoLayersVisible[numLayers - 1] = sprite.layers[numLayers - 1].isVisible
topTwoLayersVisible[numLayers] = sprite.layers[numLayers].isVisible

-- Hide the top two layers
sprite.layers[numLayers - 1].isVisible = false
sprite.layers[numLayers].isVisible = false

-- Export the sprite sheet with the remaining layers
local spriteSheetPath = app.fileSaveDialog("Export Sprite Sheet", "spritesheet.png")
if spriteSheetPath then
  sprite:renderGrid(spriteSheetPath,
                    sprite.gridBounds(),
                    sprite.gridBounds(),
                    sprite.gridBounds().origin,
                    app.Sprite.GridRenderMode.UNMERGECELS)
end

-- Restore the visibility state of the top two layers
sprite.layers[numLayers - 1].isVisible = topTwoLayersVisible[numLayers - 1]
sprite.layers[numLayers].isVisible = topTwoLayersVisible[numLayers]