The way I liked it was to implement the clone () function.
Please note that this is for Lua 5.0. I think 5.1 has more built-in object-oriented constructs.
clone = function(object, ...) local ret = {} -- clone base class if type(object)=="table" then for k,v in pairs(object) do if type(v) == "table" then v = clone(v) end -- don't clone functions, just inherit them if type(v) ~= "function" then -- mix in other objects. ret[k] = v end end end -- set metatable to object setmetatable(ret, { __index = object }) -- mix in tables for _,class in ipairs(arg) do for k,v in pairs(class) do if type(v) == "table" then v = clone(v) end -- mix in v. ret[k] = v end end return ret end
Then you define the class as a table:
Thing = { a = 1, b = 2, foo = function(self, x) print("total = ", self.a + self.b + x) end }
To create an instance or extract from it, you use clone (), and you can override it by passing them in another table (or tables) as mix-ins
myThing = clone(Thing, { a = 5, b = 10 })
The call uses the syntax:
myThing:foo(100);
This will print:
total = 115
To get a subclass, you basically define another prototype object:
BigThing = clone(Thing, { -- and override stuff. foo = function(self, x) print("hello"); end }
This method is REALLY simple, perhaps too simple, but it worked well for my project.
Brendan dowling
source share