Code
local function new( class , ... )
if ( !class ) then
error( "no Class!" )
return NULL
end
if ( class.interface ) then
error( "cant instance a interface!" )
return NULL
end
local obj = table.Copy( class )
if ( obj.ctor ) then obj:ctor( ... ) end--elseif ( obj.super.ctor ) then obj.super:ctor( ... )
return obj
end
local function class( class , extends )
if ( !class || type( class ) != "table" ) then
error( "no / invalid Class!" )
return NULL
end
if ( extends ) then
if ( extends.interface ) then
for k , v in next, extends do
if ( !class[k] && k != "interface" ) then error( "interface! " .. k .. " not implemented" ) end
end
else
local cs = table.Copy( extends )
cs.super = extends
for k ,v in next, class do cs[k] = v end
class = cs
end
end
//meta tables
return class
end
local function interface( class )
class.interface = true
return class
end
----tests----tests----tests----tests----tests----tests---
-------------------------class---------------------------
local test = class{//class
me = 1,
ctor = function( this )
print( "cool" )
end,
print = function( this )
print( this.me )
end
}
local obj = new( test )//object
obj:print( )
obj.me = 5
obj:print( )
--------------------------interface----------------------
local person = interface{//interface and its keys
name = true,
alter= true,
test = true,
}
local me = class( {
name = "",
alter = 1,
test = function( this )
print( "ich bin " .. this.alter .. " und heiße " .. this.name )
end,
ctor = function( this , name , alter )
this.name = name
this.alter = alter
end
}, person )//class implements interface
local test = new( me , "K0e" , 18 )
test:test()
local test2 = new( me , "jemand anderes" , 32 )
test2:test()
test:test()
--------------------------extend----------------------
local base_pizza = class{ //class
name = "",
preis = 1,
ctor = function( this , name , preis )
this.name = name
this.preis = preis
end
}
local magarita = class({
ctor = function( this , name , preis )
--setfenv( 1 , this )--no this 4 super!
this.super:ctor( name , preis )
end,
print = function( this )
print( this.super.preis )
print( this.super.name )
end
} , base_pizza )//class extends base_pizza
local pizza = new( magarita , "Hawaii" , 1.50 )
pizza:print()
Alles anzeigen
objektorientiertes programmieren in lua