使用 love.graphics.draw 个参数进行编码。获取异常“Bad argument #1 to 'draw'(Drawable expected, got nil)”

Coding with love.graphics.draw arguments. Get the exception " bad argument #1 to 'draw'(Drawable expected, got nil)"

最近我一直在尝试学习如何编写游戏代码,我使用 lua 5.1 作为语言,使用 love2d 作为引擎。我对两者都不熟悉,我仍在尝试学习如何使用它们,所以所有这些都是基于 Goature 在 youtube 上的教程的示例代码。这是程序的菜单部分,我得到 "states/menu/main.lua:22: bad argument #1 to 'draw'(Drawable expected, got nil)"。我知道问题出在 table 或 drawButton 函数中的参数,但我不知道问题出在哪里或如何解决。 如果有人能解释出什么问题,那就太好了。谢谢!

function load()

    love.graphics.setBackgroundColor(190, 190, 190, 255)

    imgPlay = love.graphics.newImage("Textures/start.png")
    imgPlayOn = love.graphics.newImage("Textures/start_on.png")
    imgexit = love.graphics.newImage("Textures/exit.png")
    imgexitOn = love.graphics.newImage("Textures/exit_on.png")
end

buttons = {{imgOff = imgPlay, imgOn = imgPlayOn, x = 400, y = 300 - 64, w = 256, h = 64, action = "play"},
              {imgOff = imgexit, imgOn = imgexitOn, x = 400, y = 300 + 64, w = 256, h = 64, action ="exit"}
              }
local function drawButton(highlightOff, highlightOn, x, y, w, h, mx, my)
    local ins = insideBox(mx, my, x - (w/2), y - (h/2), w, h)

    love.graphics.setColor(255, 255, 255, 255)

    if ins then
        love.graphics.draw(highlightOn, x, y, 0, 1, 1, (w/2), (h/2))
    else
        love.graphics.draw(highlightOff, x, y, 0, 1, 1, (w/2), (h/2))
    end
end

function love.update(dt)
end

function love.draw()
    local x = love.mouse.getX()
    local y = love.mouse.getY()

    for k, v in pairs (buttons) do -- v acts as an "address"
        drawButton(v.imgOff, v.imgOn, v.x, v.y, v.w, v.h, x, y) -- each elemant corresponds in the table
    end
end

问题在于您如何定义 buttons table。

当你定义你的 buttons table 时,你给每个按钮对象一个 imgOnimgOff 字段,但是当你分配它们时,你使用的变量是零。也就是说,当将 imgPlay 分配给 imgOn 的行是 运行 时,imgPlaynil 因为 love.load (您在其中分配变量 imgPlay) 还没有被调用。

我认为解决此问题的简单方法是将您的作业分配给 love.load 中的 buttons

function love.load()
    -- other code (make sure imgPlay and other variables you use have been assigned to!
    buttons = {
        -- your buttons
    }
    -- other code
end

-- buttons doesn't exist here... yet!

function love.draw()
    -- buttons exists here as love.draw is only called after love.load
end