'Attempt to index global 'object' (a nil value)

So this is the error I have been getting:

Game.lua:66: attempt to index global 'Spears' (a nil value)
stack traceback:
                         Game.lua:66: in function '_listener'

and this is some of the code, showing where the error happens:

    local Spears = {} 
    local SpearsTimer 
    local SpearsCounter = 1


    local delayTimer
    local removeListeners




end
end




local field = display.newCircle( 0, 0, 0 ) ; field.alpha = 0.3
field.name = "field"
field.x = display.contentCenterX ; field.y = display.contentCenterY
physics.addBody( field, "static", { isSensor=true, radius=320 } )






    local spawnSpears = function() 
        local Fall = math.random(display.contentWidth * -0.2, display.contentWidth * 1.2) 
        Spears[SpearsCounter] = display.newImageRect( "Spear.png", 15, 50 ) 
        Spears[SpearsCounter].x = Fall 
        Spears[SpearsCounter].y = -200  
        physics.addBody( Spears[SpearsCounter], "dynamic", {bounce = 0} ) 
        --Spears[SpearsCounter].collision = onCollision 
        --Spears[SpearsCounter]:addEventListener( "collision", Spears[SpearsCounter] ) 
        transition.to( Spears[SpearsCounter], { rotation = Spears[SpearsCounter].rotation+720, time=15000, onComplete=spinImage } ) 
        Spears[SpearsCounter].gravityScale = 0.5 
        sceneGroup:insert(Spears[SpearsCounter])
        group:insert(Spears[SpearsCounter])
        SpearsCounter = SpearsCounter + 1
    end 


   SpearsTimer = timer.performWithDelay( 5000, spawnSpears, -1 )
The Error points to line 66, which is this line of code:

        Spears[SpearsCounter] = display.newImageRect( "Spear.png", 15, 50 ) 

So what am I doing wrong?

Oh, and keep in mind that I am trying to make objects spawn randomly throughout the screen and fall/go to the center of the screen. I put Radial Gravity.



Solution 1:[1]

The problem is you have declared the

    local Spears = {}

in side a function which is not accessible outside that function. Try declaring it outside the function and access. Learn about the scope of the variables.

Solution 2:[2]

This is most likely a scope problem. This tutorial will guide you into understanding scope:

https://coronalabs.com/blog/2015/06/16/tutorial-scope-for-beginners/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kumar KS
Solution 2 Rob Miracle