Advertisement
Freack100

OO Utility

Aug 21st, 2015
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.77 KB | None | 0 0
  1. local function createClass(inherit)
  2.     return setmetatable({},{__index=inherit})
  3. end
  4.  
  5. local _type = _G.rawtype or type
  6.  
  7. _G["rawtype"] = _type
  8.  
  9. _G["type"] = function(obj)
  10.     local type_ = rawtype(obj)
  11.     if(type_ == "table") then
  12.         if(obj._CLASS_NAME_) then
  13.             return obj._CLASS_NAME_,true
  14.         end
  15.     end
  16.     return type_
  17. end
  18.  
  19. function _G.extendsFrom(from,to)
  20.     local last = ""
  21.     local cur = from
  22.     if(cur.super) then
  23.         while last ~= "BaseClass" do
  24.             last = cur._CLASS_NAME_
  25.             if(last == to) then
  26.                 return true
  27.             end
  28.             cur = cur.super
  29.         end
  30.     end
  31.     return false
  32. end
  33.  
  34. function _G.searchClassesExtending(from)
  35.     local classes = {}
  36.     for k,v in pairs(_G) do
  37.     local t,isClass = type(v)
  38.         if(isClass) then
  39.             if(extendsFrom(v,from) and t~=from) then
  40.                 table.insert(classes,v)
  41.             end
  42.         end
  43.     end
  44.     return classes
  45. end
  46.  
  47. function import(file)
  48.     local handle = fs.open(file,"r")
  49.     local cont = handle.readAll()
  50.     handle.close()
  51.     name,super = cont:match("--@Class ([^\t\n]+)"),cont:match("--@Extends ([^\t\n]+)")
  52.     local env = {}
  53.     env[name] = createClass(_G[super])
  54.     env["super"] = _G[super] or _G["BaseClass"]
  55.  
  56.     local n = [[local new = function()
  57.     return setmetatable(super:new(),{
  58.         __index=]]..name..[[
  59.         }) end
  60. ]]
  61.  
  62.     cont = n..cont
  63.     env = setmetatable(env,{__index=_G})
  64.     local f,err = loadstring(cont)
  65.     if(err) then error(err,2) end
  66.     setfenv(f,env)
  67.     f()
  68.  
  69.     _G[name] = setmetatable(env[name],{__index=_G[super]})
  70.     _G[name].super = _G[super]
  71.     _G[name]._CLASS_NAME_ = name
  72.  
  73.  
  74. end
  75.  
  76. local del = {}
  77. for k,v in pairs(_G) do
  78.     local _,y = type(v)
  79.     if(y) then del[k] = true end
  80. end
  81.  
  82. for k,v in pairs(del) do
  83.     _G[k] = nil
  84. end
  85.  
  86. _G["BaseClass"] = createClass{_OO_VERSION_ = 1,_CLASS_NAME_="BaseClass",new = function(self) return setmetatable({},_G["BaseClass"]) end}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement