3

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Yliaho
  • 117
  • 4
  • 10

1 Answers1

4

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.

Ryan Stein
  • 7,930
  • 3
  • 24
  • 38