Search code examples
lualove2d

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


recently I have been trying to learn how to code games and I'm using lua 5.1 as the language and love2d as the engine. I'm not familiar with either and I'm still trying to learn how to use them so all of this is example code based off of Goature's tutorials on youtube. This is the menu part of the program and I get "states/menu/main.lua:22: bad argument #1 to 'draw'(Drawable expected, got nil)". I know the problem is either with the table or the arguments in the drawButton function but, I don't know what the problem is or how to fix it. If anyone could explain what's wrong that would be great. Thanks!

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

Solution

  • The issue lies in how you define your buttons table.

    When you define your buttons table you give each button object a imgOn and imgOff field, but when you assign them the variables you use are nil. That is, when the line that assigns imgPlay to imgOn is run, imgPlay is nil because love.load (where you assign the variable imgPlay) hasn't been called yet.

    I'd say the easy fix to this issue is to put your assignment to buttons in love.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