Search code examples
graphicslove2d

Drawing an image loaded from other files (love2d)


So I have a "load_assets.lua" file inside my game folder along with the "main.lua". Inside the "load_assets.lua" file I have a "love.graphics.newImage(image)" and in the "main.lua" file I have the "love.graphics.draw(image)".

I've tried to create this function inside the "main.lua" file:

function love.draw(i)
    love.graphics.draw(i)
end

and this function inside the "load_assets.lua" file:

image = love.graphics.newImage(image)
lovedraw(image)

but it still doesn't seem to work.

Of course, the code is a little more complex than this, but similar:

--in "main.lua" the function is actually:

function title(lvl0)
    love.graphics.draw(lvl0)
end

--and in "load_assets" it's:

function love.load()
    lvl0 = love.graphics.newImage("lvl0.png")
end

title(lvl0)

When I run the code I get this error:

Error

title.lua:3: bad argument #1 to 'draw' (Drawable expected, got nil)


Traceback

[C]: in function 'draw'
title.lua:3: in function 'title'
main.lua:16: in main chunk
[C]: in function 'require'
[C]: in function 'xpcall'
[C]: in function 'xpcall'

Solution

  • I don't know the specifics of your code, but the following worked for me:

    load_assets.lua

    function love.load()
        lv10 = love.graphics.newImage("image.png")
    end
    

    main.lua

    require("load_assets")
    
    function title(lv10)
        love.graphics.draw(lv10)
    end
    
    function love.draw()
        title(lv10)
    end
    

    Love2d has several built in functions that you can override to create your program. Ideally, all your function calls happen from within these programs.

    So, in load_assets.lua I override the love.load() function to create lv10. By default love.load() is called exactly once, at the start of the program.

    In main.lua I define the title() function, then override love.draw() to call title(). By default, love.draw() is called every update cycle of the love engine (every frame).