addEventListener在Lua中不起作用

时间:2015-03-20 18:57:45

标签: lua addeventlistener lua-api

这是我的代码中的相关功能,我收到以下错误:

堆栈追溯:

[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()

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

您在shipSmash调用(addEventListener)中引用了本地函数enemy:addEventListener ( "tap", shipSmash ),但此时未定义该函数。您需要在预期使用它的函数之前移动shipSmash的定义。

如果您在文件上运行静态代码分析器(使用lua-inspectZeroBrane Studiothis list中的其他工具),您会看到类似这两个警告的内容,这应该会让你知道这个功能没有被正确引用:

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