尝试索引全局变量 'object' (一个空值)。

这是我一直在遇到的错误:

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

下面是一些代码,显示错误发生的位置:

    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 )
错误指向第 66 行,这是这行代码:

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

那我做错了什么呢?

哦,记住我正在尝试使对象在屏幕上随机生成并跌落/到屏幕的中心。我放置了径向重力。

点赞
用户2653067
用户2653067

问题在于你在一个函数内声明了

    local Spears = {}

这使得它在函数外不可访问。尝试在函数外声明并访问它。学习有关变量范围的知识。

2015-08-05 05:16:50
用户1870706
用户1870706

这很可能是一个作用域问题。这个教程将指导你理解作用域:

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

2015-08-10 02:54:27