Advertisement
King0fGamesYami

Object (WIP)

Dec 28th, 2015
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.64 KB | None | 0 0
  1. local function new( object )
  2.     local mt = {}
  3.     for k, v in pairs( getmetatable( object ) ) do
  4.         mt[ k ] = v
  5.     end
  6.     mt.inherits = { object.class(), unpack( mt.inherits ) }
  7.     mt.__super = object
  8.     mt.realValues = {}
  9.     return setmetatable( {}, mt )
  10. end
  11.  
  12. local Class = setmetatable( {}, {
  13.     __call = function( t, ... )
  14.         local tArgs = { ... }
  15.         if type( tArgs[ 1 ] ) == "table" and tArgs[ 1 ].name then
  16.             local n = new( t )
  17.             local mt = getmetatable( n )
  18.             mt.inherits[ 1 ] = tArgs[ 1 ].name
  19.             for k, v in pairs( tArgs[ 1 ] ) do
  20.                 n[ k ] = v
  21.             end
  22.             return n
  23.         end
  24.         return new( t )
  25.     end,
  26.  
  27.     inherits = { "Class" },
  28.  
  29.     realValues = {},
  30.  
  31.     __super = {},
  32.  
  33.     __index = function( t, k )
  34.         local temp = rawget( getmetatable( t ).realValues, k )
  35.         local result = temp ~= nil and temp or getmetatable( t ).__super[ k ]
  36.         if type( result ) == "function" then
  37.             local env = getfenv( result )
  38.             env.this, env.super = t, getmetatable( t ).__super
  39.             setfenv( result, env )
  40.         end
  41.         return result
  42.     end,
  43.  
  44.     __lt = function( left, right )
  45.         return left.extends( right.class() )
  46.     end,
  47.  
  48.     __newindex = function( t, k, v )
  49.         if type( v ) == "function" then
  50.             setfenv( v, setmetatable( {}, {__index = getfenv( v ) } ) )
  51.         end
  52.         getmetatable( t ).realValues[ k ] = v
  53.     end,
  54. })
  55.  
  56. Class.Class = function() end
  57.  
  58. Class.name = "Class"
  59.  
  60.  
  61. Class.class = function()
  62.     local inherits = getmetatable( this ).inherits
  63.     return inherits[ 1 ]
  64. end
  65.  
  66. Class.extends = function( s )
  67.     local inherits = getmetatable( this ).inherits
  68.     for k, v in pairs( inherits ) do
  69.         if v == s then
  70.             return true
  71.         end
  72.     end
  73.     return false
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement