Page 1 of 1

Getting error "background.lua:3: attempt to index local 'self' (a nil value)," how to fix this?

Posted: Sun Mar 14, 2021 7:51 pm
by oblanma
I keep getting this error despite this same thing working in my other projects, what am I doing wrong?

Here is the code for reference:

Code: Select all

local Background = {}
function Background:load()
  self.image = love.graphics.newImage("assets/background.jpg")
  self.x = 0
end

function Background:update(dt)
  if love.mouse.getX() > 420 then
      self.x = self.x - 4 * dt
  elseif love.mouse.getX() < 60 then
      self.x = self.x + 4 * dt
  end
end

function Background:draw()
  love.graphics.draw(self.image, self.x, 0, 0, 4, 4)
end

return Background
And here is my main.lua file, just in case:

Code: Select all

local Background = require("background")

function love.load()
  Background.load()
end

function love.update()
  Background.update(dt)
end

function love.draw()
  Background.draw()
end

Re: Getting error "background.lua:3: attempt to index local 'self' (a nil value)," how to fix this?

Posted: Sun Mar 14, 2021 8:58 pm
by MrFariator
You need to call those functions with a colon (:) and not with a period (.)

Code: Select all

function love.load()
  Background:load() -- note the ":"
end

function love.update()
  Background:update(dt)
end

function love.draw()
  Background:draw()
end
The colon syntax implicitly sends the table (in this case, Background) as the first parameter to the function. So these two snippets are identical:

Code: Select all

-- your original
function Background:load()
  self.image = love.graphics.newImage("assets/background.jpg")
  self.x = 0
end

-- this is syntactically the same code
function Background.load(self)
  self.image = love.graphics.newImage("assets/background.jpg")
  self.x = 0
end

-- either of these would work for calling the function
Background.load(Background)
Background:load()

Re: Re: Getting error "background.lua:3: attempt to index local 'self' (a nil value)," how to fix this?

Posted: Sun Mar 14, 2021 9:07 pm
by oblanma
Oh, oops.