Search code examples
luaaddeventlistenerlua-api

addEventListner not working in Lua


Here's the relevant functions in my code, I get the following error:

Stack traceback:

[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

My code:

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

What is the problem here ?


Solution

  • You are referencing a local function shipSmash in your addEventListener calls (enemy:addEventListener ( "tap", shipSmash )), but the function is not defined at that point. You need to move the definition of shipSmash before the functions where you expect to use it.

    If you run a static code analyzer on your file (using lua-inspect, ZeroBrane Studio, or another tool from this list), you'll see something like these two warnings among other things, which should give you an idea that this function is not properly referenced:

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