Page 1 of 1

Class help

Posted: Fri Mar 09, 2012 11:58 pm
by dotty
Hay all, I'm new to Lua, but I'm intermediate at c++ and python. Lua's classes are confusing me. I downloaded a class.lua file (http://pastie.org/3560847) which apparently makes lua working in a more OO way.

Anyway, I now have 2 files which are my work: main.lua (http://pastie.org/3560849) and obj.lua (http://pastie.org/3560852).

I can't however make 2 obj objects, only 1 ever works. Can someone explain why this is the case please, and any advice if I'm doing anything majorly wrong here.

Re: Class help

Posted: Sat Mar 10, 2012 2:30 am
by pk
Looks like you should delete require 'class' from main.lua and put it into obj.lua.

Also, posting your code as a .love that we can run is much more useful than losts of pastie links.

Re: Class help

Posted: Sun Mar 11, 2012 4:38 pm
by tentus
Your obj is lacking an init function.

Code: Select all

obj = class:new()

function obj:init()
	self.my_delta = 0
	self.x = 0
	self.y = 0
end

function obj:setDeltaPosition(x, y)
	self.x = x
	self.y = y
end

function obj:update(dt)
	self.my_delta = dt
end

function obj:draw()
	love.graphics.print(self.my_delta, self.x, self.y);
end
And then change lines 6 to 10 to this:

Code: Select all

	myobj = obj:new()
	myobj:setDeltaPosition(100,100)
	
	myobj2 = obj:new()
	myobj2:setDeltaPosition(300,300)
---

Here's another improvement you can do. Change obj.lua to this:

Code: Select all

obj = class:new()

function obj:init(d, x, y)
	self.my_delta = d or 0
	self.x = x or 0
	self.y = y or 0
end

function obj:setDeltaPosition(x, y)
	self.x = x
	self.y = y
end

function obj:update(dt)
	self.my_delta = dt
end

function obj:draw()
	love.graphics.print(self.my_delta, self.x, self.y);
end
(Notice the ors I added, and the parameters to new())

Now replace lines 6 through 10 with this:

Code: Select all

	myobj = obj:new(100,100)
	
	myobj2 = obj:new(300, 300)
All we're doing is starting up with the parameter we want, but it's much cleaner to read and a lot more efficient, once you start dealing with bigger and heavier classes.