Lua Object-oriented design

Source: Internet
Author: User

First, for the Lua language, it is not intended to be used for large-scale programming, whereasLua is targeted at small-to medium-sized programming, often as part of a large system, so it provides only a set of streamlined elements that are not available in many high-level language concepts. This makes LUA a simple and flexible lightweight language, but most of the mechanisms in high-level languages can be implemented on the basis of existing LUA.

Object-oriented is based on classes, but Lua does not provide the concept of classes, so we need to leverage the existing LUA mechanisms to implement a class-like set of concepts about OOP. The basic scenario is to use table to implement the class mechanism , and use the self parameter with the colon operation. Let's take a look at the use of the self parameter and the colon operator :

The use of the self parameter is a key element of many object-oriented languages, and most OO languages hide this mechanism so that the programmer does not have to declare this parameter (although it can still be used within a method). Lua also provides a declaration that hides this parameter by using a colon operator (a function is declared by a colon). Let's take a look at this code (which does not involve the definition of a class, but purely to explain self and colon operations):

Account = {balance = 0}function Account.withdraw (obj, v)    obj.balance = obj.balance + Venda = Accounta.withdraw (A, 100) Print (a.balance)

You can also write a function like this (replacing obj with Self can better express the semantics of the parameter):

function Account.withdraw (self, v)    self.balance = self.balance + vend

Self itself is a LUA reserved word, in order to not have to give each function declaration plus Self,lua provides a colon operator:

function Account:withdraw (v)    self.balance = Self.balance-vend

When you define a function, you change the point to a colon, and the body of the function accesses the object itself directly with the self parameter (the self parameter represents the table itself, which is the object itself). There are also two ways of writing a function call, and the two are generic:

A.withdraw (A, A:withdraw) (100)

The point operation needs to display the incoming caller itself. In fact, the effect of a colon is equivalent to adding an extra hidden parameter when the function is defined and the function is called. This approach simply provides a convenient syntax and there is nothing new in the content. We can use the DOT syntax to define the function and invoke the function with the colon syntax, and vice versa, as long as we properly handle the extra arguments.

the table in Lua is actually an object. We define a table as a prototype (equivalent to a class definition), and then other objects (also a table) access the members of the prototype table through the metatable and __index mechanisms. Here's a look at the implementation of the class:

Account = {balance = 0}--makes the table itself metatable, or you can add a MT member to the table as Metatablefunction account:new (o)    o = O or {}    Setmetatable (o, self)    self.__index = self    return oendfunction Account:withdraw (v)    self.balance = Self.balance-vendfunction account:deposit (v)    self.balance = self.balance + venda1 = ACCOUNT:NEW{}A2 = Account:new{b Alance = 100}a1:withdraw (+) print (a1.balance) print (a2.balance)

For brevity, the class itself is directly metatable to the object table. The new function above is still a bit tricky, and people who used C++/java and other languages should not be used to it. Because in a strongly typed language, programmers will try to avoid the tendency to display techniques, and use simpler, more readable notation. But when it comes to using LUA, you need to transform your thinking, especially when you're extending some concepts based on LUA, and all sorts of tricks are common and customary.

  The implementation of class inheritance is very simple, calling the new operation of the base class directly, and then adding a number of additional members or methods to the subclass:

--the class that inherits from the account (which is actually an account object), Specialacount can redefine the inherited member function, or add a new member function Specialaccount = Account:new ()--subclass instantiation, interestingly , S's metatable is specialaccounts = Specialaccount:new{limit = 1000}

Can see, in fact, the above class is also an object, just see how you understand it, when an object as a template prototype, it is a class, but at the same time, it is also an object, very random have wood.

Multiple inheritance: The idea of multiple inheritance is simple, that is, for a domain that does not exist in a subclass, it can be found in several parent classes in turn. However, this code is somewhat complex, as follows:

Named = {Name = "default"}function Named:getname () return self.name endfunction named:setname (v) self.name = v End--k is the function name, List is the parent category search = function (k, list) for    i = 1, table.getn (list) does        local v = list[i][k]        --accesses the K field of the first parent class, and the presence returns 
   if v then return v end    endend--parameter is the parent class list createclass = function (...)    c = {}    --The k in this is the domain    setmetatable (c, {__index = function (t, K) return search (K, arg)   end})        --meta used as an object Table    C.__index = c    function c:new (o)        o = O or {}        setmetatable (o, c)        return o    end        return Cendnamedaccount = Createclass (account, Named) obj = Namedaccount:new{name = "Paul"}print (Obj:getname ())

The function search indicates that a field with the name K is found in the list of parent classes.

The function createclass is used to create a multi-inheritance class with parameters as the parent class list. You can see that the object is metatable with a multiple-inheritance class, while the multiple-inheriting class finds the domain in multiple parent classes by metatable.

  the implementation of a private member: a closure-based package that encapsulates data or interfaces that you do not want to be accessed externally.

function NewAccount (initialbalance)    -This is full of private parts, which can be private data or private functions    local self = {balance = initialbalance}        Local withdraw = function (v) self.balance = self.balance-v End    Local deposit = function (v) self.balance = Self.balan Ce + V End        Local getbalance = function () return self.balance end        --the externally exposed interface is all indexed in the return table    return {withdraw = WI Thdraw, deposit = deposit, GetBalance = getbalance}enda1 = NewAccount (0) a2 = newaccount (+) A1.withdraw (+) print ( A1.getbalance ()) print (A2.getbalance ())

  a Special "object": This can be used when the object has only a single method. It is a special case of the OOP described earlier, which is not inherited but private and efficient:

function NewObject (value)    return function (action, V)        if action = = "Get" then return value        elseif action = = "se T "then value = V        Else error (" Invalid action ")        end    endendd = newObject (0) print (d (" get ")) d (" Set "," Ten ") print (d ("get"))

It can be seen from the above that the Single-method object is actually a closure. Instead of using a table, it considers a ha eucalyptus as an object.

Http://www.cnblogs.com/sifenkesi/p/3845132.html

Lua Object-oriented design (GO)

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.