LUA implements multiple inheritance

Source: Internet
Author: User

Lua supports object-oriented support primarily through table, where each table is an object, and for inheritance, LUA has a meta-table mechanism through which the setmetatble () can be used to modify the meta-table.

What is MetaTable?

MetaTable in fact is in itself can not find things, will go to the meta-table to find.

__index Meta-method:

The __index method is used to determine how a table looks when it is used as a meta-table. Its value allows the function to be a table, and the general usage is:

local obj = {}setmetatable(obj, {__index = xx})   --这样便实现了obj实现继承自xx。

For multiple inheritance, the principle is to traverse multiple parent classes, the code is as follows:

local class1 = {}function class1:new()    local obj = {}    setmetatable(obj, {__index= class1})    return objendfunction class1:print1()    print("class1:print()")endlocal class2 = {}function class2:new()    local obj = {}    setmetatable(obj, {__index= class2})    return objendfunction class2:print2()    print("class2:print()")endfunction super(k, list)    for i,v in ipairs(list) do        local ret = v[k]        if ret then            return ret        end    endendlocal class3 = {}function class3:new()    local obj = {}    local  base = {class1, class2}    --t为调用的对象,k为方法名    setmetatable(class3, {__index= function(t,k) return super(k, base) end})    setmetatable(obj, {__index = class3})    return objend

Result output:

Class1:print ()

Class2:print ()

LUA implements multiple inheritance

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.