按钮在 Lua 中不起作用 (Corona)

Buttons do not work in Lua (Corona)

我已经创建了一个游戏,它的游戏部分仍在制作中。但是,该游戏确实可以玩。我使用了有关 corona 的教程来学习如何制作菜单。菜单显示,音乐播放。但是报错:

Runtime error
addEventListener: listener cannot be nil: nil
stack traceback:
    [C]: in function 'error'
    ?: in function 'getOrCreateTable'
    ?: in function 'addEventListener'
    ?: in function 'addEventListener'
    /Users/jordanmcbride/Desktop/Lua Projects/Tapinator/main.lua:76: in function 'startButtonListeners'
    /Users/jordanmcbride/Desktop/Lua Projects/Tapinator/main.lua:53: in function 'Main'
    /Users/jordanmcbride/Desktop/Lua Projects/Tapinator/main.lua:90: in main chunk

有问题的那些行是这样的:

function startButtonListeners(action)

   if(action == 'add') then
        playButton:addEventListener('touch', playGame) -- Line 76
        creditsButton:addEventListener('touch', showCredits)
    else
        playButton:removeEventListener('touch', playGame)
        creditsButton:removeEventListener('touch', showCredits)
    end
end

第 53 行:

startButtonListeners('add')

第 90 行:

Main()

到此为止的所有代码(不包括游戏逻辑):

function Main()
    name = display.newImage('title.png', display.contentWidth / 2, 53)
    name:scale( .5, .5 )

    playButton = display.newImage('playButton.png', display.contentWidth / 2, 245)
    playButton:scale( .5, .5 )

    creditsButton = display.newImage('creditsButton.png', display.contentWidth / 2, 305)
    creditsButton:scale( .5, .5 )

    homePage = display.newGroup(name, playButton, creditsButton)

    startButtonListeners('add')
end

local showCredits = {}
function showCredits.touch(e)
    playButton.isVisible = false
creditsButton.isVisible = false
creditsView = display.newImage('credits.png', 0, display.contentHeight)

lastY = name.y
transition.to(name, {time = 300, y = display.contentHeight * 0.5 - title.height - 25})
transition.to(creditsView, {time = 300, y = display.contentHeight * 0.5 + creditsView.height, onComplete = function() creditsView:addEventListener('tap', hideCredits) end})
end

local hideCredits = {}
function hideCredits.touch(e)
    transition.to(creditsView, {time = 300, y = display.contentHeight, onComplete = function() creditsButton.isVisible = true playButton.isVisible = true creditsView:removeEventListener('tap', hideCredits) display.remove(creditsView) creditsView = nil end})
    transition.to(name, {time = 300, y = lastY});
end

function startButtonListeners(action)

    if(action == 'add') then
        playButton:addEventListener('touch', playGame)
        creditsButton:addEventListener('touch', showCredits)
    else
        playButton:removeEventListener('touch', playGame)
        creditsButton:removeEventListener('touch', showCredits)
    end
end

正如 johlo 所说,在 startButtonListener 函数中添加侦听器时未定义 playGame 函数。

此外,如果您尝试制作菜单或 UI,请尝试使用 widgets such as the newButton 小部件。它使 UI 的编码变得容易得多,并且您可以轻松添加多种效果,例如在按下按钮时更改按钮图像。