Class help

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
dotty
Prole
Posts: 1
Joined: Fri Mar 09, 2012 11:52 pm

Class help

Post 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.
User avatar
pk
Citizen
Posts: 67
Joined: Wed Dec 14, 2011 2:13 am
Location: Texas, United States
Contact:

Re: Class help

Post 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.
ALL CREATURE WILL DIE AND ALL THE THINGS WILL BE BROKEN. THAT'S THE LAW OF SAMURAI.
User avatar
tentus
Inner party member
Posts: 1060
Joined: Sun Oct 31, 2010 7:56 pm
Location: Appalachia
Contact:

Re: Class help

Post 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.
Kurosuke needs beta testers
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 4 guests