Reputation: 13
I'm trying to do OOP using the hump library in Lua for a game coded in löve 2D. Everything is working fine. However, when I try to play with my code the way bellow, a message error tells me that "self" is a nill value. Can someone tell me what I did wrong please?
Item=Class{
init=function(x,y,size)
self.x=x
self.y=y
self.size=size
self.dx=dx
self.dy=dy
self.dx2=dx2
self.dy2=dy2
end;
update=function(dt)
self.dx=self.dx+self.dx2
self.x=self.x+self.dx*dt
self.dy=self.dy+self.dy2
self.y=self.y+self.dy*dt
end;
coliide=function(ball)
return math.sqrt((self.x-ball.x)^2+(self.y-ball.y)^2)<self.size
end;
reset=function()
self.x=love.graphics.getWidth()/2
self.y=love.graphics.getHeight()/2
self.dy=0
self.dx=0
self.dy2=0
self.dx2=0
end
}
Thank you and regards
Upvotes: 0
Views: 203
Reputation: 28994
In the given snippet
Item = Class{}
Item.init=function(x,y,size)
self.x = x
end
self
is nil
because you did not define it.
In order to do what you want you have to define the function like that:
Item.init = function(self, x, y, size)
self.x = x
end
and call it like that
Item.init(Item, x, y, size)
Then self equals Item and you may index it without an error.
To make this a bit more convenient we can use something called Syntactic Sugar
Let's have a look into the Lua 5.3 Reference Manual:
A call
v:name(args)
is syntactic sugar forv.name(v,args)
, except thatv
is evaluated only once.
The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement
function t.a.b.c:f (params) body end
is syntactic sugar for
t.a.b.c.f = function (self, params) body end
Using this knowledge we can simply write:
function Item:init(x,y,size)
self.x = x
end
and call it like so:
Item:init(x,y)
Upvotes: 1
Reputation: 5867
The implicit self
argument is available to function when it was declared using colon syntax. E.g.:
Item=Class{}
function Item:init(x,y,size)
self.x = x
self.y = y
-- ...
end
Alternatively you could just add self
argument explicitly in your existing code. Just make sure you're calling it with colon syntax.
Upvotes: 0