lua实现面向对象(封装/继承/多态)
print ( "***********面向对象**********" )
print ( "*************封装************" )
Object= { }
Object. id= 1 function Object: Test ( ) print ( self. id)
end
function Object: new ( ) local obj= { } self. __index= selfsetmetatable ( obj, self) return obj
end local myObj= Object: new ( )
local myObj2= Object: new ( )
myObj. id= 3
myObj: Test ( ) myObj2. id= 2
myObj2: Test ( ) print ( "*************继承************" )
function Object: subClass ( classname) _G[ classname] = { } local obj= _G[ classname] self. __index= selfobj. base= selfsetmetatable ( obj, self)
end
Object: subClass ( "Person" )
local p1= Person: new ( )
print ( p1. id)
print ( "修改值为100" )
p1. id= 100
print ( p1. id) Object: subClass ( "Monster" )
local m1= Monster: new ( )
print ( m1. id)
print ( "修改值为200" )
m1. id= 200
print ( m1. id)
print ( "*************多态************" )
Object: subClass ( "GameObject" )
GameObject. posX= 0
GameObject. posY= 0
function GameObject: Move ( ) self. posX= self. posX+ 1 self. posY= self. posY+ 1 print ( self. posX) print ( self. posY)
end GameObject: subClass ( "Player" )
function Player: Move ( ) self. base. Move ( self)
end local b= Player: new ( ) b. posX= 3
b: Move ( )