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

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
oblanma
Prole
Posts: 3
Joined: Sat Jan 23, 2021 4:30 am

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

Post 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
MrFariator
Party member
Posts: 510
Joined: Wed Oct 05, 2016 11:53 am

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

Post 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()
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 31 guests