【问题标题】:attempt to call method 'addEventListeners' (a nil value)尝试调用方法“addEventListeners”(零值)
【发布时间】:2025-12-05 11:25:02
【问题描述】:

--这是错误

--文件:menu.lua

Line: 131
--Attempt to call method 'addEventListeners' (a nil value)
--stack traceback:
--  menu.lua:131: in function 'startButtonListeners'
--  menu.lua:179: in function <menu.lua:32> --"startButtonListeners('add')"--
--  ?: in function 'dispatchEvent'
--  ?: in function 'gotoScene'

-- 我不明白我必须把“startButtonListeners('add')”放在哪里

local sceneGroup = self.view

background = display.newImageRect( "img/bg.png", display.contentWidth, display.contentHeight )
background.anchorX = 0
background.anchorY = 0
background.x, background.y = 0, 0   

titleLogo = display.newImageRect( "img/title.png", 356, 132 )
titleLogo.x = display.contentWidth * 0.5
titleLogo.y = 150



-- button2
tasto2 = display.newImage('img/tasto2.png', 356,66)     
tasto2.x = display.contentWidth *0.5
tasto2.y = 300


sceneGroup:insert( background )
sceneGroup:insert( titleLogo )
sceneGroup:insert( tasto2 )


--listener "tap" 
function startButtonListeners(action)
    if (action == 'add')  then
        tasto2:addEventListeners ('tap', showInfo) --THIS IS LINE 131

    else
        tasto2:removeEventListeners ('tap', showInfo)

    end
end



function showInfo:tap(e)
        tasto2.isVisible = false
        titleLogo.isVisible = false
        infoView = display.newImage('img/bg.jpg', display.contentWidth *0.5, display.contentHeight *0.5)

        lastY = titleLogo.y

        transition.to(infoView, 
        {time = 400, 
        y = (display.contentHeight * 0.5) , 
        onComplete = function() 
        infoView:addEventListener('tap', hideInfo) end})
end


function hideInfo:tap(e) 
        transition.to(infoView, 
        {time = 300, 
        y = display.contentHeight + 25, 
        onComplete = function() 
            tasto2.isVisible = true
            titleLogo.isVisible = true`enter code here`
            infoView:removeEventListener('tap', hideInfo) 
            display.remove(infoView) infoView = nil end}) 
            transition.to(titleLogo, {time = 300, y = lastY}); 
end 
startButtonListeners('add')     

【问题讨论】:

  • 我不熟悉这种语言,但通常对于听众来说,您希望在创建它们后立即将它们添加到您的按钮中并传递给正在收听它们的人。如果您传递一个空值,则在单击按钮时它不会有任何通知。查看观察者模式,了解更多关于监听器如何工作的信息。
  • 我看到了这个*.com/questions/15760576/… 他把“startButtonListeners('add')”放在最后,然后关闭场景。代码非常相似:我必须激活按钮“tasto2”的侦听器,定义我的函数并在使用它之后。无事可做
  • @Steve:错误信息表明tasto2对象中没有调用addEventListeners的方法。您在评论中链接到的代码使用 addEventListener(不带复数 s)。
  • @siffiejoe:谢谢!现在运行!

标签: button lua coronasdk


【解决方案1】:

你试过 addEventListener 吗?我不认为 addEventListeners 是一个有效的函数......

【讨论】:

    【解决方案2】:

    可能是 Corona 无法从路径加载图像并返回 nil?

    【讨论】:

    • 不,不是。可以肯定的是,我已经将 infoView 'img / bg.jpg' 的图像更改为 'img / tasto2.png'。这不是问题。谢谢!