【问题标题】:Coding with love.graphics.draw arguments. Get the exception " bad argument #1 to 'draw'(Drawable expected, got nil)"使用 love.graphics.draw 参数进行编码。获取异常“错误参数 #1 到 'draw'(Drawable 预期,得到 nil)”
【发布时间】:2016-04-29 19:49:07
【问题描述】:

最近我一直在尝试学习如何编写游戏代码,我使用 lua 5.1 作为语言,使用 love2d 作为引擎。我对这两个都不熟悉,我仍在尝试学习如何使用它们,所以所有这些都是基于 Goature 在 youtube 上的教程的示例代码。这是程序的菜单部分,我得到“states/menu/main.lua:22: bad argument #1 to 'draw'(Drawable expected, got nil)”。我知道问题出在表格或 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

【问题讨论】:

    标签: lua love2d


    【解决方案1】:

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

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

    我想说解决这个问题的简单方法是把你的分配给buttonslove.load

    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
    

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 2017-04-08
    • 2020-05-19
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2019-08-16
    • 2021-07-29
    相关资源
    最近更新 更多