Lua-Object-Oriented Programming

Source: Internet
Author: User
Lua-Object-Oriented Programming

 

Lua is not a language designed for Object-Oriented purposes. Therefore, it does not directly support object-oriented programming only in the original ecological syntax, however, Lua's design still contains a lot of object-oriented ideas. Understanding them also helps to understand some of Lua's advanced mechanisms.

 

Object

A table in Lua is an object that can have function fields. In Object Oriented Programming, object methods usually use the self (or this) parameter to identify the object itself, you can use the colon (:) to implement similar functions in Lua, as shown in the following example:

Account = {balance=0}function Account:withdraw1(v)    self.balance = self.balance - vendfunction Account.withdraw2(self, v)    self.balance = self.balance - vendAccount:withdraw1(100)print(Account.balance)    Account.withdraw2(Account, 100)print(Account.balance)

In the preceding example, withdraw1 uses a colon and implicitly uses the self parameter. withdraw2 uses the dot syntax and explicitly uses the self parameter;

It can be seen that the colon is used to add an additional hidden parameter (Self) to a method definition and add an additional real parameter to a method call.

 

 

Class

In OO languages such as C ++ and python, the class syntax is used to create an object (or instance), that is, each object is an instance of a specific class.

In Lua, there is no concept of a class, that is to say, the object has no type. How can we create multiple objects with similar behaviors?

The answer is to set the _ index meta method of a table as another table through the _ index meta method of the Meta table. Then the latter method will be inherited by the former.

Example:

Humman = {age=0}function Humman:SetAge(v) self.age=v endfunction Humman:GetAge() return self.age end    Chinese = {}setmetatable(Chinese, {__index = Humman})Chinese:SetAge(76.3)print(Chinese:GetAge())

In the above example, Chinese will look for methods that do not exist in humman.

 

You can even create an object by imitating the constructor:

    class = {doc=‘hello‘}function class:new(obj)    obj = obj or {}    setmetatable(obj, self)    self.__index = self    return objendlocal a1 = class:new()print(a1.doc)

The table named class serves as a class. By calling its new method, an object with similar behavior can be returned, as shown in the example, the A1 object inherits all fields of the class.

 

 

Inheritance

In the idea of OO programming, another important concept is inheritance and derivation, that is, to allow the Child class to be derived from the parent class. In addition to inheriting the behavior of the base class, the Child class can also define its own unique behavior.

This feature is still implemented in Lua by using the properties of the _ index meta method. Only when no index field exists will the returned results of the _ index meta method be used.

Example:

Humman = {age=0}function Humman:SetAge(v) self.age=v endfunction Humman:GetAge() return self.age endfunction Humman:new(obj)    obj = obj or {}    setmetatable(obj, self)    self.__index = self    return objendChinese = Humman:new()function Chinese:SetAge(v) self.age = v*0.9 endBeijing = Chinese:new{city=‘bj‘}Beijing:SetAge(70) print(Beijing:GetAge()) -- 63

In this example, Chinese inherits from humman, But it re-defines the setage method. When setage is called in the Beijing object, the system first searches for Chinese characters before searching for humman, the setage Method of Chinese has taken effect.

 

The inheritance implementation idea provided above is to set the _ index meta method of the derived class to a table representing the base class. To implement multi-inheritance, this method is not feasible. For multi-inheritance, _ index must be implemented as a function. It must traverse all fields of the base class.

Example:

parent1 = {a="hello"}parent2 = {b="world"}local function search(field, parents)    for i=1, #parents do        local v = parents[i][field]        if v then return v end    endendfunction createClass(...)    local c = {}    local parents = {...}    setmetatable(c, {__index=function(t, field) return search(field, parents) end} )    c.__index = c    function c:new(o)        o = o or {}        setmetatable(o, c)        return o    end    return cendc = createClass(parent1, parent2)print(c.a)  -- helloprint(c.b)  -- world

 

 

 

Access permission

We know that in the C ++ class, each member has an access Tag: public, private, and protected. The access tag is used to determine whether each member in the object is visible to the outside. The common practice is to mark the data member as private and the function member as public.

Previously, we introduced that Lua objects are implemented through tables, and each field in the table can be accessed directly through indexes. Therefore, Lua does not intend to directly provide a control mechanism for access permissions to its internal fields. However, there is a way to implement access control for the Lua object.

Example:

function Humman(initialAge)    local self = {age=initialAge}    local SetAge = function(v) self.age=v end    local GetAge = function() return self.age end    return {GetAge=GetAge, SetAge=SetAge}endChinese = Humman(73)print(Chinese.GetAge()) -- 73Chinese.SetAge(80)print(Chinese.GetAge()) -- 80

In the preceding example, humman is a factory function that creates a Chinese object. Inside humman, the class State (the class member to be protected) is assigned to a local variable and the class method (that is, the class's external interface) after a table is returned to a Chinese object, the Chinese object can only indirectly operate the humman class status through the returned method, but cannot directly access them.

 

 

Single-method object

When an object has only one method, this independent method is returned as an object. For example, a stateful iterator is a single method object.

A single method object can also be used to perform different operations based on a specific parameter to implement a function similar to the scheduler, for example:

function newObject(value)    return function(action, v)    if action == "get" then return value;        elseif action == "set" then value = v        else error("invalid action")        end    endendd = newObject(0)print(d("get"))d("set", 10)print(d("get"))                 

In the preceding example, the returned single method object uses a closure.

 

Lua-Object-Oriented Programming

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.