Created
February 2, 2012 16:12
-
-
Save creationix/1724296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- The base object `Object` | |
local Object = {} | |
Object.meta = {__index = Object} | |
-- Create a new instance of this object | |
function Object:create() | |
local meta = rawget(self, "meta") | |
if not meta then error("Cannot inherit from instance object") end | |
return setmetatable({}, meta) | |
end | |
-- Create a new instance and call constructor if there is one | |
function Object:new(...) | |
local obj = self:create() | |
if type(obj.initialize) == "function" then | |
obj:initialize(...) | |
end | |
return obj | |
end | |
-- Extend this object into a new prototype object | |
function Object:extend() | |
local obj = self:create() | |
obj.meta = {__index = obj} | |
return obj | |
end | |
p("Object", Object) | |
local Rectangle = Object:extend() | |
function Rectangle:initialize(w, h) | |
self.w = w | |
self.h = h | |
end | |
function Rectangle:getArea() | |
return self.w * self.h | |
end | |
p("Rectangle", Rectangle) | |
local r = Rectangle:new(2, 3) | |
p("r, r:getArea()", r, r:getArea()) | |
local Square = Rectangle:extend() | |
function Square:initialize(w) | |
self.w = w | |
self.h = w | |
end | |
p("Square", Square) | |
local s = Square:new(4) | |
p("s, s:getArea()", s, s:getArea()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"Object" { extend = function: 0x409910c0, meta = { __index = table: 0x4098f7b8 }, create = function: 0x4098f7e0, new = function: 0x40991038 } | |
"Rectangle" { meta = { __index = table: 0x4097e528 }, initialize = function: 0x40991cb8, getArea = function: 0x40992068 } | |
"r, r:getArea()" { h = 3, w = 2 } 6 | |
"Square" { initialize = function: 0x40992cd0, meta = { __index = table: 0x40992c10 } } | |
"s, s:getArea()" { h = 4, w = 4 } 16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment