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