self not working/is nil?

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
User avatar
FlyinRabidUnicornPig
Prole
Posts: 3
Joined: Mon Jan 06, 2014 12:45 am

self not working/is nil?

Post by FlyinRabidUnicornPig »

Hey, so I'm fairly new to both Lua and to Love2D.

I wanted to recreate the hamster tutorial, but using objects and the class.lua file found on the SECS page. For some reason, I always get errors involving the self. command. I've compared with other examples and I don't see what I've been doing wrong.

Here's my main:

Code: Select all

function love.load()
   require "Hamster"
   hamster1 = Hamster:new(50,50,300)
   print("working")
end

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

function love.draw()
	hamster1.draw()
end

And the Hamster file:

Code: Select all

require "class"

Hamster = class:new()

function Hamster:init(x,y,speed)
	self.x = x
	self.y = y
	self.speed = speed
	self.image = love.graphics.newImage("hamster.png")
	print("Called!")
end

function Hamster.update(dt)
   if love.keyboard.isDown("right") then
      self.x = self.x + (self.speed * dt)
   end
   if love.keyboard.isDown("left") then
      self.x = self.x - (self.speed * dt)
   end

   if love.keyboard.isDown("down") then
      self.y = self.y + (self.speed * dt)
   end
   if love.keyboard.isDown("up") then
      self.y = self.y - (self.speed * dt)
   end
end

function Hamster.draw()
   love.graphics.draw(self.image, self.x, self.y)
end
The error is this:
"Hamster.lua:30: attempt to index global 'self' (a nil value)"

Thanks to whoever helps! :)
chanko08
Prole
Posts: 6
Joined: Sat Jan 04, 2014 9:33 pm

Re: self not working/is nil?

Post by chanko08 »

I didn't take a close look, but one thing that looks off is in all the functions of Hamster you put a dot (.) as opposed to the colon (:). Putting a colon gives an implicit 'self' argument, so that might be what you're missing.
User avatar
FlyinRabidUnicornPig
Prole
Posts: 3
Joined: Mon Jan 06, 2014 12:45 am

Re: self not working/is nil?

Post by FlyinRabidUnicornPig »

chanko08 wrote:one thing that looks off is in all the functions of Hamster you put a dot (.) as opposed to the colon (:).
THANK YOU! I put a colon in the areas where I called methods, and on the functions themselves, and now it works! Thanks a lot! :awesome:
Post Reply

Who is online

Users browsing this forum: Google [Bot], Semrush [Bot] and 9 guests