lua元表的应用也非常广泛,小到运算符重载,大到面向对象实现,一下列举了一些运算符的重载和类继承的例子:
一:运算符重载:当想将两个对象相加怎么办?
__add
: the addition (+
) operation. If any operand for an addition is not a number, Lua will try to call a metamethod. It starts by checking the first operand (even if it is a number); if that operand does not define a metamethod for__add
, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, if no metamethod is found, Lua raises an error.__sub
: the subtraction (-
) operation. Behavior similar to the addition operation.__mul
: the multiplication (*
) operation. Behavior similar to the addition operation.__div
: the division (/
) operation. Behavior similar to the addition operation.__mod
: the modulo (%
) operation. Behavior similar to the addition operation.__pow
: the exponentiation (^
) operation. Behavior similar to the addition operation.__unm
: the negation (unary-
) operation. Behavior similar to the addition operation.__idiv
: the floor division (//
) operation. Behavior similar to the addition operation.__band
: the bitwise AND (&
) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither an integer nor a float coercible to an integer (see §3.4.3).__bor
: the bitwise OR (|
) operation. Behavior similar to the bitwise AND operation.__bxor
: the bitwise exclusive OR (binary~
) operation. Behavior similar to the bitwise AND operation.__bnot
: the bitwise NOT (unary~
) operation. Behavior similar to the bitwise AND operation.__shl
: the bitwise left shift (<<
) operation. Behavior similar to the bitwise AND operation.__shr
: the bitwise right shift (>>
) operation. Behavior similar to the bitwise AND operation.__concat
: the concatenation (..
) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number (which is always coercible to a string).__len
: the length (#
) operation. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call (always adjusted to one value) is the result of the operation. If there is no metamethod but the object is a table, then Lua uses the table length operation (see §3.4.7). Otherwise, Lua raises an error.__eq
: the equal (==
) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean.__lt
: the less than (<
) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings. Moreover, the result of the call is always converted to a boolean.__le
: the less equal (<=
) operation. Behavior similar to the less than operation.__index
: The indexing access operationtable[key]
. This event happens whentable
is not a table or whenkey
is not present intable
. The metavalue is looked up in the metatable oftable
.The metavalue for this event can be either a function, a table, or any value with an
__index
metavalue. If it is a function, it is called withtable
andkey
as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, the final result is the result of indexing this metavalue withkey
. This indexing is regular, not raw, and therefore can trigger another__index
metavalue.__newindex
: The indexing assignmenttable[key] = value
. Like the index event, this event happens whentable
is not a table or whenkey
is not present intable
. The metavalue is looked up in the metatable oftable
.Like with indexing, the metavalue for this event can be either a function, a table, or any value with an
__newindex
metavalue. If it is a function, it is called withtable
,key
, andvalue
as arguments. Otherwise, Lua repeats the indexing assignment over this metavalue with the same key and value. This assignment is regular, not raw, and therefore can trigger another__newindex
metavalue.Whenever a
__newindex
metavalue is invoked, Lua does not perform the primitive assignment. If needed, the metamethod itself can call rawset to do the assignment.__call
: The call operationfunc(args)
. This event happens when Lua tries to call a non-function value (that is,func
is not a function). The metamethod is looked up infunc
. If present, the metamethod is called withfunc
as its first argument, followed by the arguments of the original call (args
). All results of the call are the results of the operation. This is the only metamethod that allows multiple results.
local a = { 1, 2, 3, 4 }
local b = { 2, 3, 4, 5 }
-- 元表
local mt = {};
mt.__add = function(a, b)
local alen = #a;
local blen = #b;
if alen ~= blen then
print("两个表的长度不同不能相加");
return;
end
local res = {};
for i = 1, alen do
res[a[i]] = a[i] + b[i];
end
return res;
end
mt.__band = function(a, b)
local alen = #a;
local blen = #b;
if alen ~= blen then
return;
end
local res = {};
for i = 1, alen do
res[i] = a[i] & b[i];
end
return res;
end
-- 元表相当于运算符重载
setmetatable(a, mt);
setmetatable(b, mt);
local c = a + b;
local d = a & b;
for k, v in ipairs(c) do
print(k, v);
end
for k, v in ipairs(d) do
print(k, v)
end
-- 设置元表
local shape = { width = 100, height = 200, x = 0, y = 0, area = 100, 4 };
-- 1:在表中查找,如果找到,返回改元素,找不到继续
-- 2:判断该表是否有元表,如果没有元表,返回nil,有元素就继续
-- 3:判断元表有没有 __index方法,如果没有返回nil,如果__index方法是一个表,则重复1,2,3,如果__index方法是一个函数,则返回该__index函数的返回值
shape.__index = function(t, key)
-- for k, v in ipairs(t) do
-- print(k, v);
-- end
print("t's len is " .. #t);
print("key is " .. key);
return shape[key];
-- return t[key];
end
shape.__tostring = function(t)
local res = "";
print("tostring function len is " .. #t);
for i = 1, #t do
res = res .. t[i] .. ','
end
return res;
end
shape.__name = function(t)
local res = "";
for i = 1, #t do
res = res .. t[i] .. ',';
end
print("__name res is " .. res);
return res;
end
-- 赋值 如果元表里面没有就在元表里面插入一个新的值
shape.__newindex = function(t, key, value)
-- print("key is " .. key);
-- print("vlaue is " .. value);
shape[key] = value;
end
local rect = { minLeft = 0, maxLeft = 100, 7 };
print(#rect);
print(rawget(rect, minLeft));
for k, v in ipairs(rect) do
print("in rect v is k is " .. k, v);
end
setmetatable(rect, shape);
-- print("width is " .. rect.width);
-- rawget 获取一个表中是否存在key
-- print(rawget(rect, width));
-- 一个在元表中不存在的话会调用 __newindex 方法来对元表进行赋值
-- rect.test = 100;
-- print('test is ' .. rect.test);
-- print("shape' test is " .. shape.test);
print("----------------");
print(rect);
print("----------------");
-- set
for k, v in pairs(_G) do
print(k, v);
end
二:类继承:主要用到的是元方法: __index
self.__index = self;这句话的意思是将Cpeople的元方法__index设置为一个表,而这个表就是 Cpeople,确保能够找到对应的属性,其实__index不一定必须是函数,也可以是nil和表,对应关系如下:
-- 1:在表中查找,如果找到,返回改元素,找不到继续
-- 2:判断该表是否有元表,如果没有元表,返回nil,有元素就继续
-- 3:判断元表有没有 __index方法,如果没有返回nil,如果__index方法是一个表,则重复1,2,3,如果__index方法是一个函数,则返回该__index函数的返回值
local Cpeople = { name = "lck", age = 12 };
-- Cpeople.new = function(o)
-- local o = o or {};
-- setmetatable(o, Cpeople);
-- Cpeople.__index = Cpeople;
-- return o;
-- end
-- local p1 = Cpeople.new();
-- print(p1.name);
-- : 的作用省略Cpeople
function Cpeople:new(o)
o = o or {};
setmetatable(o, self);
self.__index = self;
return o;
end
function Cpeople:walk()
print(self.name .. " walking");
end
local p1 = Cpeople:new();
print(p1.name, p1.age);
p1:walk();
-- 男性继承自人类
Male = {}
function Male:new(o)
local o = o or {};
setmetatable(o, self);
self.__index = self;
-- 继承 people
setmetatable(self, Cpeople);
Cpeople.__index = Cpeople;
return o;
end
local p2 = Male:new({ name = "ddd" });
p2:walk();
return Cpeople;