美文网首页
Lua 元表元方法(Metatables and Metamet

Lua 元表元方法(Metatables and Metamet

作者: 玻璃缸里的自游 | 来源:发表于2019-01-20 15:12 被阅读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则会出错。

相关文章

  • Lua 元表元方法(Metatables and Metamet

    1、Every value in Lua can have a metatable. This metatable...

  • Lua中元表的学习

    Lua本身没有面向对象的思想,但是可以根据表、元表、元方法来靠近它 一、元表与元方法的概念Lua中每个值都可具有元...

  • Lua-元表

    元表Metatable Lua提供了元表,允许我们改变table的行为,每个行为关联了对应的元方法。 例如,使用元...

  • 2017.5.26

    lua学习:metatable 元方法,元表 lua 中的任何一个值都有其预定义的一套操作,这些操作都是在元表中定...

  • Lua 元表和元方法

    table 作为 Lua 中唯一的数据结构,我们可以利用 table 实现面向对象编程中的类、继承、多重继承等等。...

  • LUA元表与元方法

    前言 元表对应的英文是metatable,元方法是metamethod。我们都知道,在C++中,两个类是无法直接相...

  • Lua实现继承

    Lua元表使用 中的__index元方法可以实现面向对象和继承关系: lua中没有类的概念,只有table,但可以...

  • 2018-08-02

    lua实现继承,重载和多态(上) *讲到lua的继承等面向对象的实现,首先得讲一下lua中的几个元方法和元表. s...

  • 2018-08-06

    lua实现继承,重载和多态(下) 上一篇讲了,lua的几个元方法和元表, 这里我们直接手动实现一个类方法, 可以创...

  • lua元表(Metatable)

    Lua 提供的元表(Metatable),允许我们改变table的行为,每个行为关联了对应的元方法。 __inde...

网友评论

      本文标题:Lua 元表元方法(Metatables and Metamet

      本文链接:https://www.haomeiwen.com/subject/grvxjqtx.html