1、简单的面向对象函数
function create(name,id)
local obj = {name = name,id = id}
function obj:setName(name)
self.name = name;
end
function obj:getName()
return self.name
end
function obj:setId(id)
self.id = id
end
function obj:getId()
return self.id
end
return obj
end
local myCreate = create("Yuxikuo",123)
print("myCreate's name:",myCreate:getName(),"myCreate's id:",myCreate.getId(myCreate))
myCreate:setId(000)
myCreate:setName("Pac")
print("myCreate's name:",myCreate:getName(),"myCreate's id:",myCreate:getId())
成员方法的定义:
function obj:method(a1,a2,...) ...end 等价于function obj.method(self,a1,a2,...) ...end还等价于obj.method = function(self,a1,a2,...) ...end
成员方法的调用
obj:method(a1,a2,...)等价于obj.method(obj,a1,a2,...)
obj:method(a1,a2,...)等价于obj.method(obj,a1,a2,...)
2、简单继承
local function CreateRobot(name,id)
local obj = {name = name, id = id}
function obj:setName(name)
self.name = name
end
function obj:getName()
return self.name
end
function obj:setId(id)
self.id = id
end
function obj:getId()
return self.id
end
return obj
end
local function createFootballRobot(name,id,position)
local obj = CreateRobot(name,id)
obj.position = position
function obj:setPosition(p)
self.position = p
end
function obj:getPosition()
return self.position
end
return obj
end
local mycreateFootballRobot = createFootballRobot("Tom",1000,"广州")
print("mycreateFootballRobot's name:",mycreateFootballRobot:getName(),"mycreate's id:",mycreateFootballRobot:getId(),mycreateFootballRobot:getPosition())
mycreateFootballRobot:setName("XXX")
mycreateFootballRobot:setId(1990)
mycreateFootballRobot:setPosition("北京")
print("mycreateFootballRobot's name:",mycreateFootballRobot:getName(),"myCreate's id:",mycreateFootballRobot:getId(),mycreateFootballRobot:getPosition())
简单继承的特点是不够动态,
1和2的运行结果如下: