猴子原创,欢迎转载。转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢!
原文地址: http://www.cocos2dev.com/?p=425
上次有个同学问我,说lua太简单了,没有什么结构,也不好做面向对象编程。其实可以这样说,Lua中的table就是一个对象。
Hero = {attack = 100} function Hero.skill(addAttack) Hero.attack = Hero.attack + addAttack end Hero.skill(20) print(Hero.attack) --> 120
oneHero = Hero; Hero = nil oneHero.skill(30) print(oneHero.attack) --> 错误,oneHero为nil
Hero = {attack = 100} function Hero.skill(self,addAttack) self.attack = self.attack + addAttack end oneHero = Hero; Hero = nil oneHero.skill(oneHero,30) print(oneHero.attack) --> 130
Hero = {attack = 100} function Hero:skill(addAttack) self.attack = self.attack + addAttack end oneHero = Hero; Hero = nil oneHero:skill(30) print(oneHero.attack) --> 130
Hero = {} function Hero:new(o) o = o or {} setmetatable(o,self) self.__index = self return o end function Hero:skill(addAttack) self.attack = self.attack + addAttack end oneHero = Hero:new{attack = 90} oneHero:skill(10) print(oneHero.attack) -->100
Hero = {attack = 0} function Hero:new(o) o = o or {} setmetatable(o,self) self.__index = self return o end function Hero:skill(addAttack) self.attack = self.attack + addAttack end function Hero:injured(loseAttack) if loseAttack > self.attack then error"not engouth attack" end self.attack = self.attack - loseAttack end HumanHero = Hero:new() oneHero = HumanHero:new{attack = 100} oneHero:skill(10) print(oneHero.attack) -->110