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.
Class help
Re: Class help
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.
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.
- tentus
- Inner party member
- Posts: 1060
- Joined: Sun Oct 31, 2010 7:56 pm
- Location: Appalachia
- Contact:
Re: Class help
Your obj is lacking an init function.
And then change lines 6 to 10 to this:
---
Here's another improvement you can do. Change obj.lua to this: (Notice the ors I added, and the parameters to new())
Now replace lines 6 through 10 with this:
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.
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
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
Now replace lines 6 through 10 with this:
Code: Select all
myobj = obj:new(100,100)
myobj2 = obj:new(300, 300)
Kurosuke needs beta testers
Who is online
Users browsing this forum: Ahrefs [Bot] and 4 guests