Page 1 of 1

More OOP in Lua/Love

Posted: Wed Oct 14, 2009 7:42 pm
by dtaylorl
I realize that this forum is full of topics full of how to use objects in lua + love, so at the risk of being redundant (but I do hope I'm not) here is my question:
Has anyone had any luck using OOP in love as outlined here? http://www.lua.org/pil/16.html

At a simple level it appears that I should be able to define a class like this:

Code: Select all

function MyClass:new (o)
      o = o or {}   -- create object if user does not provide one
      setmetatable(o, self)
      self.__index = self
      return o
end

function MyClass:subtract (v)
      self.anumber = self.anumber - v
end
And use code like this to create a new object of that class:

Code: Select all

myobject = MyClass:new(anumber = 10)
And call a method on my object like this:

Code: Select all

myobject:subtract(7)
--myobject.anumber now = 3
Am I on track so far or am I missing something?
Okay, next thing. It should be okay to do this right?

Code: Select all

mytable = {}
mytable[1] = MyClass:new(anumber = 20)
mytable[1]:subtract(10)
--mytable[1].anumber now = 10
Does that make sense? I'm doing something similar in my own program but its not working, instead I am getting an error: "attempt to call method 'subtract' (a nil value)" which would indicate that the object isn't pointing to the method in the class when it should be. Did I miss something. Any help is very appreciated!

(Note: This isn't the actual code in my program, but the reason I'm using these examples is that I want to make sure I have the principals down)

Re: More OOP in Lua/Love

Posted: Wed Oct 14, 2009 8:12 pm
by Robin
I think you need to do this for it to work:
myobject = MyClass:new{anumber = 10}
Otherwise, it's hard to tell without the code you're actually using.

EDIT: you might want to take a look at SECS.

Re: More OOP in Lua/Love

Posted: Wed Oct 14, 2009 8:46 pm
by zugamifk
I've been using this implementation for my game and it works perfectly. It's very compact and very easy to use.

Re: More OOP in Lua/Love

Posted: Wed Oct 14, 2009 11:57 pm
by dtaylorl
zugamifk wrote:I've been using this implementation for my game and it works perfectly. It's very compact and very easy to use.
Thanks for the link. The top part of this article shows how to do the same thing I was trying to do.

I think I've got it figured out. It looks like it was a simple syntax error. I had:

Code: Select all

self._index = self
Instead of:

Code: Select all

self.__index = self