Hard work and perseverance.
Development environment: Mac OSX 10.9.3
Cocos Code IDE:V1.0.0.RC0
Cocos2d-x-3.2rc0
COCOS2DX provides a tool function for class inheritance, in the engine of the/cocos/scripting/lua-bindings/script directory has a named Extern.lua, specifically how to use us to see the code.
Using Lua for object-oriented programming, the Declaration method and the calling method are unified with colons, and the invocation of the attribute is all used for the dot number.
Create a new Lua file in the project named Herorole.lua. This is the Herorole class that we define. The implementation code is as follows:
Herorole = Class ("Herorole")
Herorole.__index = Herorole
-hero attribute
Herorole.name = nil -name
of the person Herorole.level = nil--its own rank
--the function of a colon can be passed an argument, self, equivalent to C + + 's This
function herorole:extend (target)
Local t = Tolua.getpeer (target)
if not T
and then T = {}
tolua.setpeer (target, T)
end
setmetatable (T, Herorole)
return target
end
--Create Herorole object method
function Herorole:createherorole (_imagenamehero , _name, _level)
Local sprite = Herorole:extend (cc. Sprite:create (_imagenamehero))
sprite.name = _name
sprite.level = _level
return sprite
end
--Change name
function herorole:setheroname (value)
self.name = value
End
--Get name
function Herorole:getheroname ()
return self.name
end
--Set level
function Herorole:setherolevel (value)
Self.level = value
End
-Gets the rank
function herorole:getherolevel ()
return self.level
End
In Main.lua we create the object with the following code:
Local function Myinit ()
require "Src/herorole"
--Create Dogobj object
Local dogobj = Herorole:createherorole ("res/ Dog.png "," Dog ",
dogobj:setposition (SIZE.WIDTH/2,SIZE.HEIGHT/2)
mainlayer:addchild (dogobj)
Cclog ("Dog Object name = =%s, Leval = =%d", Dogobj:getheroname (), Dogobj:getherolevel ())
--[lua-print] Dog Object name = = Dog, Leval = =
Dogobj:setheroname ("BigDog")--Change the hero name
Dogobj:setherolevel (88) --Change the hero level
Cclog ("BigDog Object name = =%s, Leval = =%d", Dogobj:getheroname (), Dogobj:getherolevel ())
--[ Lua-print] BigDog Object name = = BigDog, Leval = =-
-Create Catobj object
Local catobj = Herorole:createherorole ("res/c Rop.png "," Cat ",
catobj:setposition (SIZE.WIDTH/2,SIZE.HEIGHT/4)
mainlayer:addchild (catobj)
Cclog ("Cat object name = =%s, Leval = =%d", Catobj:getheroname (), Catobj:getherolevel ())
--[lua-print] Cat Object Name = = Cat, Leval = =
End