[Cocos2d-x3.2 Game Development] Lua class, inheritance, object-oriented

Source: Internet
Author: User
Tags addchild metabase

1. Classes in Lua

In Lua, there is actually no class, and some are only tables, and inheritance between classes means that the tables of the parent class are connected together, if no attributes or methods are found in the derived class, you can use the meta-table to find the parent class.

2. Attributes of classes in Lua

Classa = {width = 10, Height = 10}

Classa = {}

Classa. width = 10

Classa. Height = 10

Both methods can be called by clicking self. width.

3. Class Methods

Function box: collsion () -- by default, the first parameter hides and transmits self. xxx call properties and method endfunction box. create (Self) -- The parameter self must be manually passed; otherwise, self cannot be used. xxx call attributes and method end
You can use ":" and "." To declare and call a function, and use "." To call a property "."


4. Usage of classes and meta tables

When Lua looks for a table element, the following three steps are involved:

. Search in the table. If this element is found, it is returned. If this element is not found, continue.

. Determine whether the table has a metabase. If no metabase exists, Nil is returned.

4. 3. determine whether the meta-table has the _ index method. If the _ index method is nil, Nil is returned. If the _ index method is a table, the values 1, 2, and 3 are repeated; if the _ index method is a function, the return value of the function is returned.

For example:

Father = {House = 1} son = {car = 1} setretriable (son, father) -- set son's retriable to fatherprint (son. House)
The output is nil. If the code is changed

Father = {House = 1} father. _ Index = Father -- point the father _ index method to son = {car = 1} setretriable (son, father) print (son. house)
The output result is 1.

This explains why we often see the following in the cocos2dx class:

local Box = class("Box", function(filename)        return cc.Sprite:create(filename)    end)Box.__index = Box
Set the _ index method of the box meta-table as your own. When the derived class "smallbox" is derived from "box", if the properties and methods that cannot be found in the smallbox, retrieve the meta-table, of course, it is not directly retrieved from the meta-table. It is the _ index under the meta-table. If _ index is nil, Nil is returned. If _ index is a table, search for the corresponding attributes and methods in the table indicated by the _ index method.

For details, refer to: Lua table element search process (how does the meta-table and _ index methods work)

5. Classes in cocos2dx

Lua is not object-oriented. Cocos has prepared the Lua end function of class for us. For details, refer to the quick class function. There are examples in it.

-- [[-- Create a class ~~~ Lua -- defines the base class named shape local shape = Class ("shape") -- ctor () is the class constructor, which calls shape. new () automatically executes function shape: ctor (shapename) self when creating a shape object instance. shapename = shapename printf ("shape: ctor (% s)", self. shapename) end -- defines a method named draw () for shape. Function shape: Draw () printf ("Draw % s", self. shapename) end ---- circle is the inheritance class of shape. Local Circle = Class ("circle", shape) function circle: ctor () -- if the inheritance class overwrites the ctor () constructor, required Manually call the parent class constructor-class name. super can access the circle of the parent class of the specified class. super. ctor (self, "circle") self. radius = 100 endfunction circle: setradius (RADIUS) self. radius = radiusend -- override function circle: Draw () printf ("Draw % s, raidus = % 0.2f", self. shapename, self. raidus) end -- local rectangle = Class ("rectangle", shape) function rectangle: ctor () rectangle. super. ctor (self, "rectangle") end -- local Circle = circle. new () -- output: Shape: Ctor (circle) circle: setraidus (200) circle: Draw () -- output: draw circle, radius = 200.00 local rectangle = rectangle. new () -- output: shape: ctor (rectangle) rectangle: Draw () -- output: Draw rectangle ~~~ ### Advanced usage class () not only defines pure Lua classes, but also inherits classes from C ++ objects. For example, if you need to create a toolbar and automatically arrange existing buttons when adding buttons, you can use the following code :~~~ Lua -- from CC. the toolbar class derived from the Node object, which has cc. all node attributes and behaviors: Local toolbar = Class ("toolbar", function () return display. newnode () -- returns a CC. node object end) -- constructor function toolbar: ctor () self. buttons ={} -- use a table to record all buttons end -- add a button and automatically set the button position function toolbar: addbutton (button) -- add the button object to table self. buttons [# self. buttons + 1] = button -- add the button object to CC. node to display the button-because the toolbar is from CC. node, so you can use addchi LD () method self: addchild (button) -- Adjust the positions of all buttons according to the number of buttons: Local x = 0 for _, button in ipairs (self. buttons) Do button: setposition (x, 0) -- Sort the buttons in sequence. Each button is separated by 10 points x = x + button: getcontentsize (). width + 10 endend ~~~ This usage of class () allows us to expand any behavior based on the C ++ object. Since it is inheritance, You can naturally override the methods of C ++ objects :~~~ Luafunction toolbar: setposition (x, y) -- Because CC is overwritten in the toolbar inheritance class. the setposition () method of the Node object -- so we must use the following form to call CC. the original setposition () method of node getretriable (Self ). setposition (self, x, y) printf ("x = % 0.2f, y = % 0.2f", x, y) end ~~~ ** Note: ** the methods covered by the Lua inheritance class cannot be called from C ++. That is to say, when the C ++ code calls the setposition () method of the CC. Node object, the toolbar: setposition () method defined in Lua is not executed. @ Param string classname class name @ Param [mixed super] parent class or function for creating object instances @ return table] function class (classname, super) Local supertype = type (Super) local CLS if supertype ~ = "Function" and supertype ~ = "Table" then supertype = nil super = nil end if supertype = "function" or (super and super. _ ctype = 1) then -- inherited from native C ++ object CLS ={} if supertype = "table" then -- Copy fields from super for K, V in pairs (Super) Do CLS [k] = V end Cls. _ create = super. _ create Cls. super = super else Cls. _ create = super Cls. ctor = function () end Cls. _ cname = classname Cls. _ ctype = 1 function Cls. new (...) local instance = Cls. _ create (...) -- Copy fields from class to native object for K, V in pairs (CLS) Do instance [k] = V end instance. class = CLS instance: ctor (...) return instance end else -- inherited from Lua object if super then CLS ={} setretriable (CLS, {__ Index = super}) CLS. super = super else CLS = {ctor = function () end} end Cls. _ cname = classname Cls. _ ctype = 2 -- Lua Cls. _ Index = CLS function Cls. new (...) local instance = setretriable ({}, CLs) instance. class = CLS instance: ctor (...) return instance end return clsend

If the input is a parent class, the CLS. New function is called, The instance is created, and the ctor constructor is called.

6. Call an instance:

Assume that the sprite class is derived from a Cocos.

-- Class can pass 1 and 2 parameters -- @ Param class name, internal record only, generally, it is the same as the returned class name. -- @ Param: If parameter 2 is passed, the current function is used as the constructor. If no parameter is set, the default constructor local box = Class ("box ", function (filename) return CC. sprite: Create (filename) end -- set the default metadata method of the meta-table -- when accessing a field that does not exist in the table, the interpreter searches for the metadata method of _ index, otherwise return Nil -- mostly used to inherit http://blog.csdn.net/q277055799/article/details/8463883Box.__index = boxbox. isdead = false -- Define attribute -- Constructor (automatically called) -- any parameter xxx can be passed during external constructor. new (...) function box: ctor (pic_path) Local function onnodeevent (event) If "enter" = event then box: onenter (pic_path) elseif "exit" = event then box: onexit () end end self: registerscripthandler (onnodeevent) Local function onupdate () end self: scheduleupdatewithprioritylua (onupdate, 0) endfunction box: onenter (pic_path) endfunction box: onexit () endfunction box. create (parent, position) Local box = Box. new ("Data/box.png") parent: addchild (box) return boxendreturn box

If it is a table, you can directly use

local Bomb = class("Bomb")


7. In our common cocos2dx examples, there are a lot of extend and tolua. getpeer usage:

local TimelineTestScene = class("TimelineTestScene")TimelineTestScene.__index = TimelineTestScenefunction TimelineTestScene.extend(target)    local t = tolua.getpeer(target)    if not t then        t = {}        tolua.setpeer(target, t)    end    setmetatable(t, TimelineTestScene)    return targetendfunction TimelineTestScene.create()    local scene = TimelineTestScene.extend(cc.Scene:create())    return scene   end

When tolua. getpeer is used, its function is actually equivalent to calling the class, so stay away from extend.

local TimelineTestScene = class("TimelineTestScene", cc.Scene)TimelineTestScene.__index = TimelineTestScene






[Cocos2d-x3.2 Game Development] Lua class, inheritance, object-oriented

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.