As a Java-born program, long time to do Lua, repeat some work, especially want to use inheritance. It's actually very simple. Because I have a large part of the scene, the background is the same, so I intend to do a parent class.
It is important to note that if a subclass has a function with the same name as the parent class, it will be overwritten unless the. Super method is called manually.
The key code is two places, all in a subclass.
1 when creating a scene:
Local Scenebase = Import ("app.scenes.SceneBase")local activityscene = Class ( " Activityscene ", Scenebase)
2 in the constructor of the subclass, you call the parent class
-- This is the key .
Super simple, why no one used before, with the more convenient ah, easy to maintain, save a lot of manpower it. The following is the complete code for two files.
Parent class:
LocalCommimgpath ="#images/common/ui/"LocalScenebase = Class ("Scenebase",function() returnDisplay.newscene ("Scenebase")End)functionScenebase:ctor ()Print("Scenebase:ctor") Self:addsprite ()EndfunctionScenebase:addsprite ()Print("Scenebase:addsprite") Self.menubgheight= Zysize.scale *98Self.menubgwidth= Display.width-zysize.scalew * - --backgroundCc.ui.UIImage.new (Commimgpath."beijing.jpg"): Setlayoutsize (Display.width+ zysize.scalew* -, Display.height + zysize.scale* -): Align (display. CENTER, Display.cx, display.cy): AddTo (self) cc.ui.UIImage.new (commimgpath.."Tongyongmianban3.png", {scale9 =true}): Setlayoutsize (Display.width-zysize.scalew*Ten, Display.size.height-self.menubgheight-zysize.scale *Ten):p os (Zysize.scalew*5, Self.menubgheight + Zysize.scale *3): AddTo (self) cc.ui.UIImage.new (commimgpath)."Diban2.np.png", {scale9 =true}): Setlayoutsize (Display.width, Self.menubgheight): AddTo (self)EndreturnScenebase
Sub-class:
Local Scenebase = Import ("app.scenes.SceneBase")local activityscene = Class ( " Activityscene " , Scenebase) function activityscene:ctor () -- This is the key . End return Activityscene
Inheritance in Lua