Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local super_t = {}
- local stack = {}
- local super_mt = {
- __index = function(obj, field)
- local cls = stack[#stack].class.super
- while(cls) do
- if cls.public[field] then return cls.public[field] end
- if cls.protected[field] then return cls.protected[field] end
- cls = cls.super
- end
- return nil
- end
- }
- --setmetatable(super_t, super_mt)
- local stack_mt = {
- __index = function(obj, field)
- if #stack > 0 then
- return stack[#stack][field]
- else return _G[field]
- end
- end,
- __newindex = function(obj, field, value)
- if #stack > 0 then stack[#stack][field] = value
- else _G[field] = value
- end
- end
- }
- local Object_idx = function(obj, field)
- local cls = obj.class
- local f
- if field == "super" then
- return stack[#stack].super
- elseif field == "this" then
- return stack[#stack]
- end
- if obj == super_t then cls = cls.super end
- if obj == _ENV and cls.private[field] then f = cls.private[field]
- else
- while cls do
- if cls.public[field] then
- f = cls.public[field]
- break
- elseif obj == _ENV and cls.protected[field] then
- f = cls.protected[field]
- break
- end
- cls = cls.super
- end
- end
- if f == nil then return _G[field] end
- if type(f) == "function" then
- return function(...)
- table.insert(stack, obj)
- local ret = table.pack(f(...))
- table.remove(stack)
- return table.unpack(ret, 1, ret.n)
- end
- end
- return f
- end
- setmetatable(super_t, super_mt)
- local function create(t,e)
- if t then
- local f,err = load("return"..t,nil,nil,e)
- if f then return f()
- else print(err)
- end
- end
- return {}
- end
- local classes = {}
- --local setmetatable = setmetatable
- function class(name)
- local super
- local e = {}
- setmetatable(e, stack_mt)
- local function func(o)
- if type(o) == "string" then
- super = o
- elseif type(o) == "table" then
- o.super = super and classes[super] or classes.Object
- o.public = create(o.public, e)
- o.private = create(o.private, e)
- o.protected = create(o.protected, e)
- classes[name] = o
- _G[name] = o
- end
- return func
- end
- return func
- end
- _G.class = class
- class "Object" {
- public = [[{
- __init = function(...)
- local chain = {}
- local cls = class
- while cls do
- table.insert(chain, cls)
- cls = cls.super
- end
- while #chain > 0 do
- cls = chain[#chain]
- if cls.init then cls.init(...) end
- table.remove(chain)
- end
- end,
- instanceof = function(c)
- if type(c) == "string" then c = classes[c] end
- if c then
- local cls = class
- while cls do
- if cls == c then return true end
- end
- end
- return false
- end
- }]]
- }
- function new(class)
- local cls = {}
- cls.class = classes[class] or classes.Object
- cls.super = super_t
- local cls_mt = {__index = Object_idx, __call = function(...)
- cls.__init(...)
- return cls
- end}
- setmetatable(cls, cls_mt)
- return cls
- end
- _G.new = new
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement