Search code examples
functionlualove2d

Lua: attempt to call global 'rectangle_draw' (a nil value)


I have two Lua files, one of which is main.lua:

require "player"
require "level"

function love.load()

end

function love.draw()
    rectangle_draw()
end

and another called player.lua:

function rectangle_draw()
    love.graphics.setColor(223, 202, 79)
    love.graphics.rectangle("fill", 20, 20, 32, 48)
end

As you can see, I'm trying to use the rectangle_draw() inside of love.draw() function, hoping it to draw a rectangle in specific location etc etc, but whenever I try to run my little program I get this error:

attempt to call global 'rectangle_draw' (a nil value)

Traceback

main.lua:9: in function 'draw'
[C]: in function 'xpcall'

What am I doing wrong?


Solution

  • You are not exporting any functions from player.lua. The correct way would be to do it like this:

    player.lua

    local M = {}
    
    function M.rectangle_draw()
        love.graphics.setColor(223, 202, 79)
        love.graphics.rectangle("fill", 20, 20, 32, 48)
    end
    
    return M
    

    main.lua

    local player = require "player"
    require "level"
    
    function love.load()
    
    end
    
    function love.draw()
        player.rectangle_draw()
    end
    

    Please see this section of the Lua manual, and this page on the Lua users wiki for more information about how modules and require work.