Page 1 of 1

self not working/is nil?

Posted: Mon Jan 06, 2014 1:02 am
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! :)

Re: self not working/is nil?

Posted: Mon Jan 06, 2014 1:16 am
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.

Re: self not working/is nil?

Posted: Mon Jan 06, 2014 1:22 am
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: