Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --
- --[[
- by: Molinko
- Create classes with multiple inheritance.
- Keep it flippin' simple..
- Updated: created var 'parents' in function 'Class' instead or the messy 'arg' table
- -- thanks to 'theoriginalbit' for that catch.
- ]]
- function Class( class, ... )
- local parents = { ... }
- class = class or {}
- class.__index = class
- class_mt = {
- -- look into list of parents for member
- __index = function( t, k )
- if #parents > 0 then
- for _, par in pairs( parents ) do
- if par[k] then
- t[k] = par[k] -- store member for faster secondary lookup
- return par[k]
- end
- end
- end
- return nil
- end,
- -- report class designation
- __tostring = function( t )
- return t.className
- end,
- -- create constructor metamethod. Usage: myClass( ... ), calls myClass:new( ... ).
- __call = function( t, ... )
- return t:new( ... )
- end,
- }
- -- Create instance constructor
- function class:new( o )
- return setmetatable( o or {}, self )
- end
- -- derp, derp
- function class:getParents()
- return parents
- end
- return setmetatable( class, class_mt )
- end
- -- Base class to inherit general methods for most classes
- local Object = Class{ className = "Base_class_Object" }
- function Object:printClass()
- return "class: '" .. self.className .. "'"
- end
- -- Person class
- local Person = Class{ className = "Person_class" }
- function Person:intro()
- print( "Hello, my name is '" .. self.name .. "'" )
- end
- -- Derived Class 'Wizard' inherits from parents: 'Object' & 'Person'
- local Wizard = Class( { className = "Wizard_class" }, Object, Person )
- --[[
- Giving the class instances basic metamethods is easy enough. Don't overwrite the __index method though
- as you will break the chain of inheritance.
- ]]
- Wizard.__tostring = function( t )
- return t:printClass()
- end
- -- Create class instance. optionally called with Wizard( ... ) using metamethod
- local w1 = Wizard:new{ name = 'Paul, the amazing.' }
- -- testing
- print(w1) -- calls Wizard.__tostring(), output --> "class: 'Wizard_class'"
- w1:intro() -- output --> "Hello, my name is 'Paul, the amazing.'"
- print(w1:getParents()) -- output --> table of Class parents
- print(Wizard) -- calls Wizard_mt.__tostring() output --> 'Wizard_class'
- --
Advertisement
Add Comment
Please, Sign In to add comment