addEventListener 在 Lua 中不工作

addEventListner not working in Lua

这是我代码中的相关函数,我得到以下错误:

堆栈回溯:

[C]: in function 'error'
?: in function 'getOrCreateTable'
?: in function 'addEventListener'
?: in function 'addEventListener'
main.lua:26: in function 'createPlayScreen'
main.lua:79: in main chunk

我的代码:

-- set up forward references
local spawnEnemy
--create play screen
local function createPlayScreen()
    local background = display.newImage("SpaceBackground.jpg")
    background.x = centerX
    background.y = -100
    background.alpha = 0
    background:addEventListener ( "tap", shipSmash )

    local planet = display.newImage("Earth.png")
    planet.x = centerX
    planet.y = display.contentHeight+60
    planet.alpha = .2
    planet.xScale = 2
    planet.yScale = 2
    planet:addEventListener ( "tap", shipSmash )

    transition.to(background, {time = 2000, alpha = 1, y = centerY, x = centerX})


    local function showTitle()
        local gameTitle = display.newImage("gametitle.png")
        gameTitle.alpha = 0
        gameTitle:scale(4,4)
        transition.to(gameTitle, {time=500, alpha = 1, xScale = 1, yScale = 1})
        spawnEnemy()

    end
    transition.to(planet, {time = 2000, xScale = .75, yScale = .75, alpha = 1, y = centerY, onComplete = showTitle})
end

--game functions
function spawnEnemy()
    local enemy = display.newImage("asteroid.png")
    enemy.x = math.random(20, display.contentWidth-20)
    enemy.y = math.random(20, display.contentHeight-20)
    enemy.alpha = 0
    transition.to(enemy, {time = 200 , alpha =1})
    enemy:addEventListener ( "tap", shipSmash )


end
local function shipSmash(event)
    local obj = event.target
    display.remove(obj)
    return true
end

createPlayScreen()
startGame()

这里有什么问题?

您在 addEventListener 调用 (enemy:addEventListener ( "tap", shipSmash )) 中引用了一个本地函数 shipSmash,但该函数此时尚未定义。您需要将 shipSmash 的定义移到您希望使用它的函数之前。

如果您 运行 在您的文件上使用静态代码分析器(使用 lua-inspect, ZeroBrane Studio, or another tool from this list),您会看到类似于这两个警告的内容,这应该让您知道此函数未正确引用:

file.lua:6: first use of unknown global variable 'shipSmash'
file.lua:41: unused local function 'shipSmash'