self not working/is nil?
Posted: Mon Jan 06, 2014 1:02 am
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:
And the Hamster file:
The error is this:
"Hamster.lua:30: attempt to index global 'self' (a nil value)"
Thanks to whoever helps!
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
"Hamster.lua:30: attempt to index global 'self' (a nil value)"
Thanks to whoever helps!