More OOP in Lua/Love
Posted: Wed Oct 14, 2009 7:42 pm
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:
And use code like this to create a new object of that class:
And call a method on my object like this:
Am I on track so far or am I missing something?
Okay, next thing. It should be okay to do this right?
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)
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
Code: Select all
myobject = MyClass:new(anumber = 10)
Code: Select all
myobject:subtract(7)
--myobject.anumber now = 3
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
(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)