luacoronasdk

Why is my event handler not allowing me to access event.target?


I'm setting up an inventory management system in a new Corona game. I'm testing the initial setup by creating a sample displayObject in a scene and then changing the visibility of that object on tap. The simulator throws me an error when I try, it says "Attempt to index local 'event' (a nil value)."

I tried changing the listener from a function listener to a table listener, but the same error persists. I've read the relevant Corona documentation as well as all of the Corona-related results I could find on the site, but none of the solutions seemed to apply to my particular situation (my setup already appears to be in line with what the other solutions suggest).

The game has several files, but the relevant parts here are:

inventory.lua

local composer = require( "composer" )

local I = {}


--Identifies what to do when an object is clicked
function I:clickRouter( event )
  event.target.isVisible = false --this is the line that prompts the error
return true
end

return I

sceneOne.lua

local composer = require( "composer" )
local inventoryManager = require( "inventory" )

local scene = composer.newScene()

function scene:create( event )

    local sceneGroup = self.view

        local obj = display.newImageRect(sceneGroup, "images.xcassets/scObj.png", 32, 32)
        obj.num = 1
        obj:addEventListener("tap", inventoryManager.clickRouter)

end

--...other irrelevant code omitted here

I expect, on tap, for the image to disappear. Instead, it throws the aforementioned error message. I think the error may have to do with how the files are interacting with each other, but I can't figure out what it is.


Solution

  • Okay, figured this out:

    As per this answer and this conversation, I'd been declaring the clickRouter function as a method instead of a regular function, so there was an implicit "self" parameter that was causing what I'd attempted to call the "event" to instead just be null.

    Changing the function from:

    function I:clickRouter(event)
    

    to

    function I.clickRouter(event)
    

    resolved my issue.