Cocos2d-x Lua游戏开发之Lua oo 的实现

来源:互联网 发布:网络个人信息泄露案例 编辑:程序博客网 时间:2024/05/17 12:53
一些面向对象的语言中提供了类的概念,作为创建对象的模版。在这些语言里面。对象是类的实例,lua通过table也可以实现类的使用。--建立父类AnimalAnimal = {size,--动物大小       成员变量声明,不赋值为nilage,--动物年龄color = "yellow",--动物颜色sex,--动物性别,这个可以有??new = function ( self,object )object = object or {}--判断object是否为空,nil就会创建一个空的tablesetmetatable(object,self)--设置animal基类为元表,算是继承的方法self.__index = self --同上return objectend,sleep = function ( self,pram )--lua支持:运算符,代替.运算符和显示selfprint(pram,"想要好好的睡觉")--人类尤其是,程序员,记住睡觉,no nuo no dieend,run = function ( self,pram )print(pram,"想要好好的运动")--人类尤其是,程序员,记住运动,no nuo no dieend,setAge = function ( self,age )--继承oc之set,get方法,看后面可否写成宏self.age = age--两个参数print("setAge=",self.age)return self.ageend,getAge = function ( self )print("getAge=",self.age)return self.ageend,getColor = function ( self )print("getColor=",self.color)return self.colorend}Cat = Animal:new()--创建一个空对象Cat:sleep("cat")Cat.age = 22Cat:setAge(0)Cat:getAge()Cat:getColor()Snake = Animal:new{age = 33}Snake:sleep("snake")Snake:getAge()function Snake:sleep( animal )--子类重写方法,即可实现子类自身print("snake 有了一个自己的小窝来睡觉")endSnake:sleep("snake")


csdn不支持lua,但是看着又不舒服,还是传张图片吧。使用的sublimetext




1 0
原创粉丝点击