Lua 元表元方法(Metatables and Metamet

2019-01-20  本文已影响0人  玻璃缸里的自游

1、Every value in Lua can have a metatable. This metatable is an ordinary Lua table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable.

2、The key for each event in a metatable is a string with the event name prefixed by two underscores; the corresponding values are called metamethods. Unless stated otherwise, metamethods should be function values.

3、metamethods :

__add(+)、__sub(-)、__mul(*)、__div(/)、__mod(%)、__pow(^)、__idiv(//)、__band(&)、__bor(|)、__bxor(binary)、__bnot(unary)、__shl(<<)、__shr(>>)、__concat(..)、__len(#)、__eq(==)、__lt(<)、__le(<=)、__index()、__newindex()、__call()

4、A program can modify the behavior of the length operator for any value but strings through the __len metamethod

5、例子:


tA = {1, 3}

tB = {5, 7}

tC = {9, 11}

--tSum = tA + tB + tC

mt = {}

mt.__add = function(t1, t2)

    for _, item in ipairs(t2) do

        table.insert(t1, item)

    end

return t1

end

setmetatable(tA, mt)

tSum = tA + tB + tC

for k, v in ipairs(tSum) do

    print(v)

end

说明:Lua在遇到操作符时会查操作符前面表相应metatable的metamethod.因此,

tSum = tB + tA则会出错。

上一篇 下一篇

猜你喜欢

热点阅读